#!/usr/bin/env python3
"""Real login with CUROGRAM_AGENT_USERNAME/PASSWORD (the creds the MCP server
uses) + source='Dashboard'. Read-only. No secrets printed."""
import json, urllib.request, urllib.error
def read_key(k):
    for line in open("/home/claude/.config/amd-agent/credentials.env"):
        if line.startswith(k + "="): return line[len(k) + 1:].rstrip("\n")
    return ""
USER = read_key("CUROGRAM_AGENT_USERNAME")
PW = read_key("CUROGRAM_AGENT_PASSWORD")
EP = "https://authentication.curogram.com/graphql"
LOGIN = ("mutation Login($email: Email!, $password: String!, $source: LoginPage!) {"
         " login(email: $email, password: $password, source: $source) {"
         " ... on MfaListSchema { mfa { title send id } challenge { value expiresAt } }"
         " ... on ProviderTokenSchema { expiresAt accountId } } }")
body = json.dumps({"operationName": "Login", "query": LOGIN,
    "variables": {"email": USER, "password": PW, "source": "Dashboard"}}).encode()
req = urllib.request.Request(EP, data=body, method="POST", headers={
    "Content-Type": "application/json", "Accept": "application/json",
    "X-Curogram-Frontend": "web"})
try:
    with urllib.request.urlopen(req, timeout=20) as r:
        sc = r.getheader("Set-Cookie") or ""
        bod = json.loads(r.read().decode("utf-8") or "{}")
        st = r.status
except urllib.error.HTTPError as e:
    st = e.code; sc = ""
    try: bod = json.loads(e.read().decode("utf-8", "replace"))
    except: bod = {}
errs = bod.get("errors") or []
lo = (bod.get("data") or {}).get("login") or {}
fields = list(lo.keys()) if isinstance(lo, dict) else []
print(json.dumps({"status": st,
    "login_ok": st == 200 and not errs and bool(lo),
    "fields": fields,
    "mfa": isinstance(lo.get("mfa"), list) and len(lo.get("mfa") or []) > 0,
    "set_cookie": bool(sc),
    "has_xsrf_in_setcookie": "XSRF-TOKEN" in sc,
    "err": (errs[0].get("message")[:90] if errs else None)}))
