#!/usr/bin/env python3
"""Confirm source='Dashboard' is the valid LoginPage value by doing a real
login on authentication.curogram.com with the NEW password. Prints outcome
flags + login response field type. 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 ""
NEW = read_key("AMD_PASSWORD")
USER = read_key("CUROGRAM_AGENT_USERNAME")
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 } } }")
def login(src, pw):
    body = json.dumps({"operationName": "Login", "query": LOGIN,
        "variables": {"email": USER, "password": pw, "source": src}}).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 = dict(r.getheaders()).get("Set-Cookie", "")
            return r.status, json.loads(r.read().decode("utf-8") or "{}"), bool(sc)
    except urllib.error.HTTPError as e:
        raw = e.read().decode("utf-8", "replace")
        try: return e.code, json.loads(raw), False
        except: return e.code, {"raw": raw[:200]}, False
s, r, hascookie = login("Dashboard", NEW)
errs = r.get("errors") or []
login_obj = (r.get("data") or {}).get("login") or {}
fields = list(login_obj.keys()) if isinstance(login_obj, dict) else []
print(json.dumps({"source": "Dashboard", "status": s,
    "login_ok": s == 200 and not errs and bool(login_obj),
    "fields": fields,
    "mfa_present": isinstance(login_obj.get("mfa"), list) and len(login_obj.get("mfa") or []) > 0,
    "accountId_present": "accountId" in fields,
    "set_cookie_on_response": hascookie,
    "err": (errs[0].get("message")[:80] if errs else None)}))
