#!/usr/bin/env python3
"""List all .js chunk URLs referenced by the live app (from performance/network
+ the index). Then fetch each over HTTP and grep for the LoginPage enum
definition and any enum member values. Read-only, no creds."""
import json, urllib.request, re
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 "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.get("result", {})
# Get the webpack chunk map by evaluating the runtime's chunk URL builder.
JS = r"""
(function(){
  try {
    // angular/webpack: __webpack_require__.u maps chunkId -> filename
    var u = (typeof __webpack_require__!=='undefined' && __webpack_require__.u);
    var p = (typeof __webpack_require__!=='undefined' && __webpack_require__.p) || '/';
    if(!u){
      // find any global webpack require
      for(var g in window){ try{ if(window[g] && window[g].u && window[g].p){ u=window[g].u; p=window[g].p; break; } }catch(e){} }
    }
    var base = location.origin + '/';
    var urls = [];
    if(u){
      for(var i=0;i<3000;i++){ try{ var f=u(i); if(f && /\.js$/.test(f)) urls.push((p&&/^https?:|^\//.test(p)?'':base)+ (p||'') + f); }catch(e){} }
    }
    return JSON.stringify({count:urls.length, p:p, sample:urls.slice(0,5), urls:urls.slice(0,400)});
  } catch(e){ return 'ERR '+e; }
})()
"""
r = call("Runtime.evaluate", {"expression": JS, "returnByValue": True, "timeout": 8000})
val = r.get("result", {}).get("value", "")
print("CHUNKMAP", str(val)[:600])
try:
    obj = json.loads(val); urls = obj.get("urls", [])
except Exception:
    urls = []
ws.close()
origin = "https://app.curogram.com/"
enum_re = re.compile(r"LoginPage[\s\S]{0,300}")
member_re = re.compile(r'\b([A-Z][A-Z_]{2,})\s*=\s*["\']([A-Za-z_]+)["\']')
found = 0
for u in urls:
    if not u.startswith("http"):
        u = origin + u.lstrip("/")
    try:
        src = urllib.request.urlopen(u, timeout=12).read().decode("utf-8", "replace")
    except Exception:
        continue
    if "LoginPage" not in src:
        continue
    print("HASLOGINPAGE", u.split("/")[-1])
    for m in enum_re.finditer(src):
        s = re.sub(r"\s+", " ", m.group(0))[:300]
        print("  CTX", s)
        found += 1
        if found > 8: break
    if found > 8: break
print("done")
