import json
from datetime import datetime, timezone
from pathlib import Path
from urllib.parse import urlsplit
from playwright.sync_api import sync_playwright

log = Path("<local path>")

def write(kind, **fields):
    entry = {"utc": datetime.now(timezone.utc).isoformat(), "kind": kind, **fields}
    with log.open("a") as f:
        f.write(json.dumps(entry) + "\n")
    print(json.dumps(entry), flush=True)

with sync_playwright() as p:
    browser = p.chromium.connect_over_cdp("http://localhost:9224")
    page = browser.contexts[0].pages[0]

    def relevant(url):
        host = urlsplit(url).netloc
        return "execute-api" in host or host.startswith("api.")

    def request(req):
        if relevant(req.url):
            write("request", method=req.method, path=urlsplit(req.url).path)

    def response(res):
        if relevant(res.url):
            fields = {}
            if res.request.method == "POST":
                try:
                    body = res.json()
                    fields = {k: body[k] for k in
                              ("mediaId", "status", "conversationId", "jobId")
                              if k in body}
                except Exception:
                    pass
            write("response", method=res.request.method,
                  path=urlsplit(res.url).path, status=res.status, **fields)

    page.on("request", request)
    page.on("response", response)
    page.on("pageerror", lambda e: write("pageerror", message=str(e)))
    write("ready")
    while True:
        page.wait_for_timeout(500)
