#!/usr/bin/env python3
# Read-only CDP probe with in-process PHI redaction.
# Only GETs /json/version and /json/list. No websocket attach, no nav.
import json
import urllib.request
from urllib.parse import urlsplit

BASE = "http://127.0.0.1:9222"


def get(path):
    req = urllib.request.Request(BASE + path, method="GET")
    with urllib.request.urlopen(req, timeout=5) as r:
        return json.loads(r.read().decode("utf-8", "replace"))


def redact_host(url):
    if not url:
        return "(no url)"
    try:
        s = urlsplit(url)
    except Exception:
        return "(unparseable)"
    if not s.scheme or not s.netloc:
        return f"{(s.scheme + '://') if s.scheme else ''}{s.netloc or '(non-web)'}"
    seg = [p for p in s.path.split("/") if p]
    first = ("/" + seg[0] + "/...") if seg else "/"
    return f"{s.scheme}://{s.netloc}{first}"


def redact_ws_hostport(url):
    if not url:
        return "(none)"
    try:
        s = urlsplit(url)
        return f"{s.hostname}:{s.port}  [token redacted]"
    except Exception:
        return "(unparseable)"


def main():
    out = []
    try:
        v = get("/json/version")
        out.append("CDP responded: YES")
        out.append("Browser: " + str(v.get("Browser", "?")))
        out.append("ws host:port: " + redact_ws_hostport(v.get("webSocketDebuggerUrl", "")))
    except Exception as e:
        out.append("CDP /json/version FAILED: " + type(e).__name__ + ": " + str(e)[:120])

    targets = None
    for p in ("/json/list", "/json"):
        try:
            targets = get(p)
            out.append("targets from " + p + ": " + str(len(targets)))
            break
        except Exception as e:
            out.append("GET " + p + " FAILED: " + type(e).__name__)
    out.append("--- TARGETS (type | redacted-host) ---")
    if isinstance(targets, list):
        for t in targets:
            ttype = t.get("type", "?")
            host = redact_host(t.get("url", ""))
            out.append(f"{ttype} | {host}")
    print("\n".join(out))


if __name__ == "__main__":
    main()
