#!/usr/bin/env python3
"""Harvest the live Curogram session cookie via CDP and inject CUROGRAM_COOKIE
(+ a placeholder CUROGRAM_XSRF_TOKEN) into ~/.config/curogram-mcp.env, mode
0600. This is the MFA fallback: the service account is MFA-gated so programmatic
login can't complete OTP; the MCP server honors a pre-harvested cookie.

The api-v2 read endpoints accept cookie-only auth (no real XSRF-TOKEN cookie
exists in this session), so XSRF is set to a harmless non-empty placeholder
purely to satisfy the server's `cookie && xsrf` fallback guard.

NO secret values are printed. Existing non-cookie lines are preserved.
"""
import json, os, urllib.request
from websocket import create_connection

ENV = os.path.expanduser("~/.config/curogram-mcp.env")
XSRF_PLACEHOLDER = "cdp-cookie-session-no-xsrf"

tabs = json.loads(urllib.request.urlopen("http://localhost:9223/json", timeout=8).read())
page = next(t for t in tabs if t.get("type") == "page" and "curogram.com" in (t.get("url") or "").lower())
ws = create_connection(page["webSocketDebuggerUrl"], timeout=10)
ws.send(json.dumps({"id": 1, "method": "Network.getAllCookies"}))
while True:
    m = json.loads(ws.recv())
    if m.get("id") == 1:
        res = m["result"]; break
ws.close()
ck = {c["name"]: c["value"] for c in res.get("cookies", []) if "curogram" in c.get("domain", "")}
if "CurogramPracticeToken" not in ck:
    raise SystemExit("ERROR: no CurogramPracticeToken cookie found; not logged in")
# Only the Curogram auth cookies matter; drop analytics/socket noise so the
# Cookie header stays clean. (SOCKETCOOKIE/_ga contain | and $ that complicate
# shell-sourcing anyway.)
WANTED = ["CurogramPracticeToken", "CurogramPracticeLoggedIn", "CurogramPracticeCurrent"]
cookie = "; ".join(f"{k}={ck[k]}" for k in WANTED if k in ck)

# Read existing env, drop any prior cookie/xsrf lines, keep the rest.
lines = []
if os.path.exists(ENV):
    with open(ENV) as f:
        for ln in f:
            if ln.startswith("CUROGRAM_COOKIE=") or ln.startswith("CUROGRAM_XSRF_TOKEN="):
                continue
            lines.append(ln.rstrip("\n"))
# Single-quote values so `set -a; source` handles spaces/specials safely. The
# JWT + cookie values contain no single quotes, so plain single-quoting is safe.
if "'" in cookie:
    raise SystemExit("ERROR: cookie value contains a single quote; aborting")
lines.append(f"CUROGRAM_COOKIE='{cookie}'")
lines.append(f"CUROGRAM_XSRF_TOKEN='{XSRF_PLACEHOLDER}'")

fd = os.open(ENV, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w") as f:
    f.write("\n".join(lines) + "\n")
os.chmod(ENV, 0o600)
print(json.dumps({"injected": True, "cookie_names": sorted(ck.keys()),
    "cookie_len": len(cookie), "xsrf": "placeholder", "env_mode": oct(os.stat(ENV).st_mode & 0o777)}))
