#!/usr/bin/env python3
"""Use CDP Runtime.evaluate to walk webpack modules in the live app and dump
any object that looks like the LoginPage enum (keys/values). Read-only."""
import json, urllib.request
from websocket import create_connection
tabs = json.loads(urllib.request.urlopen("http://localhost:9223/json", timeout=8).read())
page = next(t for t in tabs if t.get("type") == "page" and "app.curogram.com" in (t.get("url") or "").lower())
ws = create_connection(page["webSocketDebuggerUrl"], timeout=25)
_id = [0]
def call(method, params=None):
    _id[0] += 1; mid = _id[0]
    ws.send(json.dumps({"id": mid, "method": method, "params": params or {}}))
    while True:
        m = json.loads(ws.recv())
        if m.get("id") == mid:
            return m
JS = r"""
(function(){
  var out = [];
  try {
    var req = (window.webpackChunkcurogram_web || window.webpackChunk || null);
  } catch(e){}
  // Brute force: scan all properties of window for enum-like objects
  function looksLikeEnum(o){
    if(!o || typeof o!=='object') return false;
    var ks = Object.keys(o);
    if(ks.length<1 || ks.length>20) return false;
    // string->string map, upper-case-ish keys
    return ks.every(function(k){return typeof o[k]==='string';}) &&
           ks.some(function(k){return /PROVIDER|PRACTICE|PATIENT|LOGIN|WEB|DASH/i.test(k+o[k]);});
  }
  // Try to pull from any module cache by scanning function sources is hard;
  // instead grep all loaded scripts text already failed. Try DOM: nothing.
  // Last resort: search global registry for LoginPage token.
  for(var key in window){
    try{
      var v = window[key];
      if(looksLikeEnum(v)){ out.push({k:key, map:v}); }
    }catch(e){}
    if(out.length>40) break;
  }
  return JSON.stringify(out).slice(0,4000);
})()
"""
r = call("Runtime.evaluate", {"expression": JS, "returnByValue": True, "timeout": 8000})
print(json.dumps(r.get("result", {}), indent=2)[:4000])
ws.close()
