#!/usr/bin/env python3
"""
SidePay Studio (Mac Pilot v5.0.0) CLI
Commands:
  sidepay-cli doctor
  sidepay-cli list
  sidepay-cli pair <spk_live_...>
  sidepay-cli whoami
  sidepay-cli run <slug>
  sidepay-cli record-upload [slug]
  sidepay-cli submit <session_id> <file.json>
"""
import json, os, shutil, subprocess, sys, urllib.request
from pathlib import Path

CONFIG_PATH = Path.home() / ".sidepay" / "config.json"


def load_cfg() -> dict:
    cfg = {"origin": "https://sidepay.ai", "apiKey": ""}
    if CONFIG_PATH.exists():
        try:
            cfg.update(json.loads(CONFIG_PATH.read_text()))
        except Exception:
            pass
    if os.environ.get("SIDEPAY_ORIGIN"):
        cfg["origin"] = os.environ["SIDEPAY_ORIGIN"].rstrip("/")
    if os.environ.get("SIDEPAY_API_KEY"):
        cfg["apiKey"] = os.environ["SIDEPAY_API_KEY"].strip()
    return cfg


def save_cfg(cfg: dict) -> None:
    CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True)
    CONFIG_PATH.write_text(json.dumps(cfg, indent=2))


def auth_headers(cfg: dict, content_type: str = "application/json") -> dict:
    h = {"Content-Type": content_type}
    if cfg.get("apiKey"):
        h["Authorization"] = f"Bearer {cfg['apiKey']}"
    return h


def cmd_doctor() -> int:
    cfg = load_cfg()
    tools = ["blender", "claude", "agy", "cursor", "codex", "git", "python3", "node"]
    report = {t: shutil.which(t) for t in tools}
    print(f"SidePay Studio CLI v5.0.0 — Origin: {cfg['origin']} | Bridge: http://127.0.0.1:49152")
    print(f"  Paired Token : {'YES' if cfg.get('apiKey') else 'NO (run `sidepay-cli pair <spk_...>`) '}")
    for k, v in report.items():
        status = f"FOUND ({v})" if v else "optional"
        print(f"  - {k:10s}: {status}")
    return 0


def cmd_pair(token: str) -> int:
    cfg = load_cfg()
    cfg["apiKey"] = token.strip()
    save_cfg(cfg)
    print(f"Saved SidePay pairing token to {CONFIG_PATH}")
    return cmd_whoami()


def cmd_whoami() -> int:
    cfg = load_cfg()
    req = urllib.request.Request(
        f"{cfg['origin']}/api/auth/me",
        headers=auth_headers(cfg),
        method="GET",
    )
    with urllib.request.urlopen(req, timeout=15) as resp:
        data = json.loads(resp.read().decode())
    if not data.get("authenticated"):
        print("Not paired to an account yet. Run `sidepay-cli pair <spk_live_...>`.", file=sys.stderr)
        return 1
    u = data["user"]
    print(f"Authenticated : {u['name']} ({u['email']})")
    print(f"Available     : ${u['availableBalanceCents'] / 100:.2f}")
    return 0


def cmd_list() -> int:
    cfg = load_cfg()
    req = urllib.request.Request(f"{cfg['origin']}/api/briefs", method="GET")
    with urllib.request.urlopen(req, timeout=15) as resp:
        data = json.loads(resp.read().decode())
    print(f"Open Tasks on {cfg['origin']}:")
    for item in data.get("starterTasks", []):
        print(f"  [${item['rewardCents']/100:4.2f}] {item['slug']:22s} — {item['title']}")
    return 0


def cmd_run(slug: str) -> int:
    cfg = load_cfg()
    run_dir = Path.home() / "SidePay" / "runs" / slug
    run_dir.mkdir(parents=True, exist_ok=True)
    req = urllib.request.Request(
        f"{cfg['origin']}/api/runs/start",
        data=json.dumps({"slug": slug, "agentHarness": "sidepay-cli"}).encode(),
        headers=auth_headers(cfg),
        method="POST",
    )
    with urllib.request.urlopen(req, timeout=15) as resp:
        session = json.loads(resp.read().decode())
    (run_dir / "session.json").write_text(json.dumps(session, indent=2))
    print(f"Claimed Session : {session['sessionId']} (Seed #{session['seed']})")
    print(f"Workspace       : {run_dir}")
    return 0


def cmd_record_upload(slug: str) -> int:
    cfg = load_cfg()
    script_dir = Path(__file__).resolve().parent
    candidates = [
        script_dir / "SidePay.app" / "Contents" / "MacOS" / "SidePay",
        Path("/Applications/SidePay.app/Contents/MacOS/SidePay"),
        Path.home() / "Applications" / "SidePay.app" / "Contents" / "MacOS" / "SidePay",
    ]
    bin_path = next((p for p in candidates if p.exists()), None)
    if not bin_path:
        print("Error: SidePay.app binary not found.", file=sys.stderr)
        return 1
    cmd = [str(bin_path), "--record-upload", slug, "--origin", cfg["origin"]]
    if cfg.get("apiKey"):
        cmd.extend(["--token", cfg["apiKey"]])
    res = subprocess.run(cmd, check=False)
    return res.returncode


def cmd_submit(session_id: str, sol_path: str) -> int:
    cfg = load_cfg()
    raw_text = Path(sol_path).read_text()
    try:
        sol = json.loads(raw_text)
        payload = json.dumps({"sessionId": session_id, "agentHarness": "sidepay-cli", "solution": sol}).encode()
    except Exception:
        payload = json.dumps({"sessionId": session_id, "agentHarness": "sidepay-cli", "rawAnswerText": raw_text}).encode()
    req = urllib.request.Request(
        f"{cfg['origin']}/api/runs/submit",
        data=payload,
        headers=auth_headers(cfg),
        method="POST",
    )
    with urllib.request.urlopen(req, timeout=20) as resp:
        out = json.loads(resp.read().decode())
    print(json.dumps(out, indent=2))
    return 0 if out.get("passed") else 2


def main() -> int:
    argv = sys.argv[1:]
    if not argv or argv[0] in ("-h", "--help", "help"):
        print(__doc__.strip())
        return 0
    if argv[0] == "doctor":
        return cmd_doctor()
    if argv[0] == "list":
        return cmd_list()
    if argv[0] == "pair" and len(argv) >= 2:
        return cmd_pair(argv[1])
    if argv[0] == "whoami":
        return cmd_whoami()
    if argv[0] == "run" and len(argv) >= 2:
        return cmd_run(argv[1])
    if argv[0] == "record-upload":
        return cmd_record_upload(argv[1] if len(argv) >= 2 else "pool-photonic-quantum")
    if argv[0] == "submit" and len(argv) >= 3:
        return cmd_submit(argv[1], argv[2])
    print("Invalid arguments. Run `sidepay-cli --help`.", file=sys.stderr)
    return 1


if __name__ == "__main__":
    sys.exit(main())
