#!/usr/bin/env python3
"""List Curogram cookie NAMES + domains from CDP 9223 (values redacted).
Helps locate the XSRF token cookie. Prints no secret values."""
import json
import sys
import urllib.request

from websocket import create_connection

PORT = 9223


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()

rows = []
for c in res.get("cookies", []):
    dom = c.get("domain") or ""
    if "curogram" in dom.lower():
        rows.append({
            "name": c.get("name"),
            "domain": dom,
            "path": c.get("path"),
            "httpOnly": c.get("httpOnly"),
            "len": len(c.get("value") or ""),
        })
print(json.dumps({"tab_url": tab.get("url"), "count": len(rows), "cookies": rows}, indent=0))
