#!/usr/bin/env python3
"""
watcher_helper.py -- Pushes command results back to GitHub via API.
Uses direct GitHub REST API calls instead of git commit/push.
This avoids git state issues where local index differs from remote,
which was causing unrelated files (WhatsApp/, etc.) to be deleted.
"""
import json
import sys
import os
import base64
import urllib.request
import urllib.error
from datetime import datetime

PAT  = "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"
REPO = "Jake-Culberson/Claud-Code"
BASE = f"https://api.github.com/repos/{REPO}/contents"

def api_get(path):
    url = f"{BASE}/{path}"
    req = urllib.request.Request(url, headers={
        "Authorization": f"Bearer {PAT}",
        "Content-Type": "application/json",
    })
    try:
        with urllib.request.urlopen(req) as resp:
            return json.loads(resp.read())
    except Exception as e:
        return {}

def api_put(path, content_str, msg, sha=None):
    url = f"{BASE}/{path}"
    b64 = base64.b64encode(content_str.encode()).decode()
    payload = {"message": msg, "content": b64}
    if sha:
        payload["sha"] = sha
    data = json.dumps(payload).encode()
    req = urllib.request.Request(url, data=data, method="PUT", headers={
        "Authorization": f"Bearer {PAT}",
        "Content-Type": "application/json",
    })
    try:
        with urllib.request.urlopen(req) as resp:
            d = json.loads(resp.read())
            return d.get("commit", {}).get("sha", "")[:12]
    except urllib.error.HTTPError as e:
        body = e.read().decode()
        print(f"API PUT error {e.code}: {body[:200]}", file=sys.stderr)
        return ""

def main():
    cmd_id    = sys.argv[1] if len(sys.argv) > 1 else "unknown"
    exit_code = int(sys.argv[2]) if len(sys.argv) > 2 else 0

    # Read output from temp file
    output = ""
    try:
        with open("/tmp/cmd_output.txt", "r") as f:
            output = f.read()
    except Exception:
        output = "(no output)"

    now = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
    result = {
        "cmd_id":      cmd_id,
        "executed_at": now,
        "exit_code":   exit_code,
        "output":      output,
    }
    result_str = json.dumps(result, indent=2)
    msg = f"vm: result for {cmd_id} at {datetime.utcnow().strftime('%Y-%m-%d %H:%M')}"

    # Push ONLY to Stock_Bot/feedback/result.json via API
    # No git commit -- this prevents accidental deletion of other repo files
    d = api_get("Stock_Bot/feedback/result.json")
    sha = d.get("sha", "")
    commit = api_put("Stock_Bot/feedback/result.json", result_str, msg, sha)
    if commit:
        print(f"Feedback written OK (commit {commit})")
    else:
        print("Feedback write FAILED", file=sys.stderr)
        sys.exit(1)

if __name__ == "__main__":
    main()
