#!/usr/bin/env python3
"""Print the agent account identity from current-session (name fields only)."""
import json
import urllib.request

from websocket import create_connection

PORT = 9223
SESSION_URL = "https://api-v2.curogram.com/authenticate/current-session"


def http_json(url):
    with urllib.request.urlopen(url, timeout=10) as r:
        return json.loads(r.read().decode())


def cdp_call(ws, method, params=None, _id=1):
    ws.send(json.dumps({"id": _id, "method": method, "params": params or {}}))
    while True:
        m = json.loads(ws.recv())
        if m.get("id") == _id:
            return m.get("result", {})


tabs = [t for t in http_json(f"http://localhost:{PORT}/json") if t.get("type") == "page"]
tab = next((t for t in tabs if "curogram.com" in (t.get("url") or "").lower()), tabs[0])
ws = create_connection(tab["webSocketDebuggerUrl"], timeout=10)
try:
    res = cdp_call(ws, "Network.getAllCookies")
finally:
    ws.close()
cookies = [c for c in res.get("cookies", []) if "curogram" in (c.get("domain") or "").lower()]
cookie_header = "; ".join(f"{c['name']}={c['value']}" for c in cookies)

req = urllib.request.Request(SESSION_URL, headers={
    "X-Curogram-Frontend": "web", "Accept": "application/json",
    "Content-Type": "application/json", "Cookie": cookie_header}, method="GET")
with urllib.request.urlopen(req, timeout=20) as resp:
    data = json.loads(resp.read().decode())

acct = data.get("account", {})
cp = data.get("currentPractice", {})
print(json.dumps({
    "account": {k: acct.get(k) for k in
                ("displayName", "firstName", "lastName", "userType", "id")},
    "currentPractice_name": cp.get("name") if isinstance(cp, dict) else None,
    "currentPractice_keys": list(cp.keys()) if isinstance(cp, dict) else None,
}))
