#!/usr/bin/env python3
"""Probe candidate LoginPage enum values to find the valid one. Uses the NEW
password so a valid enum yields login success; an invalid enum yields the
BAD_USER_INPUT enum error. Prints per-candidate outcome (no secrets)."""
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 } } }")
CANDS = ["PROVIDER_WEB", "WEB", "PROVIDERWEB", "DASHBOARD", "PROVIDER_DASHBOARD",
         "PROVIDER_PORTAL", "PORTAL", "APP", "PROVIDER_APP", "ADMIN", "DESKTOP",
         "PRACTICE", "PRACTICE_WEB", "PROVIDER_LOGIN", "LOGIN", "MAIN"]
def login(src):
    body = json.dumps({"operationName": "Login", "query": LOGIN,
        "variables": {"email": USER, "password": NEW, "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:
            return r.status, json.loads(r.read().decode("utf-8") or "{}")
    except urllib.error.HTTPError as e:
        raw = e.read().decode("utf-8", "replace")
        try: return e.code, json.loads(raw)
        except: return e.code, {"raw": raw[:200]}
for c in CANDS:
    s, r = login(c)
    errs = r.get("errors") or []
    msg = (errs[0].get("message") if errs else "")[:90]
    enum_bad = "does not exist in" in (msg or "")
    login_ok = s == 200 and not errs and bool(r.get("data", {}).get("login"))
    fields = []
    try: fields = list((r.get("data") or {}).get("login", {}).keys())
    except Exception: pass
    print(json.dumps({"source": c, "status": s, "enum_invalid": enum_bad,
        "login_ok": login_ok, "fields": fields, "msg": None if enum_bad else msg}))
    if login_ok or (s == 200 and not enum_bad):
        print(">>> VALID ENUM:", c); break
