#!/usr/bin/env python3
"""
worker-ua 2-test validation
- Vanilla Playwright (no CDP)
- CDP-attached Chrome (with debugger)

Compares navigator.userAgent vs WorkerNavigator.userAgent across conditions.
A mismatch (or worker UA having wrong Chrome version) indicates bot tampering.
"""
import json
import sys
from playwright.sync_api import sync_playwright

DEMO_URL = "http://127.0.0.1:3457/spikes/worker-ua/demo.html"
RESULTS = {}

def run(condition, attach_cdp=False):
    print(f"\n=== {condition.upper()} ===")
    with sync_playwright() as p:
        # Launch browser with or without CDP-attached debugger
        args = ["--no-sandbox"]
        if attach_cdp:
            # Launch with a remote debugging port so we can attach
            browser = p.chromium.launch(
                headless=True,
                args=args + ["--remote-debugging-port=9223"],
            )
        else:
            browser = p.chromium.launch(headless=True, args=args)

        ctx = browser.new_context()
        page = ctx.new_page()

        if attach_cdp:
            # Attach via CDP (simulates DevTools-open or automation-tool attachment)
            cdp = ctx.new_cdp_session(page)
            cdp.send("Runtime.enable")

        page.goto(DEMO_URL)
        page.wait_for_function("window.__dbReady === true", timeout=10000)
        result = page.evaluate("window.__dbResult")

        print(f"  main UA:    {result['mainUA'][:80]}")
        print(f"  worker UA:  {result['workerUA'][:80]}")
        print(f"  main platform:    {result['mainPlatform']}")
        print(f"  worker platform:  {result['workerPlatform']}")
        print(f"  uaMatch:           {result['uaMatch']}")
        print(f"  platformMatch:     {result['platformMatch']}")
        print(f"  vendorMatch:       {result['vendorMatch']}")
        print(f"  versionMatch:      {result['versionMatch']} (main={result['mainVer']}, worker={result['workerVer']})")
        print(f"  main vendor:       '{result['mainVendor']}'")
        print(f"  worker vendor:     '{result['workerVendor']}'")
        print(f"  platformHint:      {result['platformHint']}")

        RESULTS[condition] = result
        ctx.close()
        browser.close()

if __name__ == "__main__":
    run("vanilla", attach_cdp=False)
    run("cdp", attach_cdp=True)

    # Compare
    print("\n=== COMPARISON ===")
    v = RESULTS["vanilla"]
    c = RESULTS["cdp"]
    all_match = all([
        v["uaMatch"] == c["uaMatch"],
        v["platformMatch"] == c["platformMatch"],
        v["vendorMatch"] == c["vendorMatch"],
        v["versionMatch"] == c["versionMatch"],
        v["platformHint"] == c["platformHint"],
    ])
    print(f"  All checks identical across conditions: {all_match}")
    print(f"  Vanilla findings: uaMatch={v['uaMatch']}, platform={v['platformMatch']}, ver={v['versionMatch']}")
    print(f"  CDP findings:     uaMatch={c['uaMatch']}, platform={c['platformMatch']}, ver={c['versionMatch']}")

    # Verdict
    if all_match and v["uaMatch"] and v["platformMatch"] and v["versionMatch"]:
        print("\n  VERDICT: NO SIGNAL — both conditions show main/worker UA consistent (real-browser behavior)")
        print("  This signal does NOT discriminate. Do not ship.")
        sys.exit(0)
    elif all_match and not v["uaMatch"]:
        print("\n  VERDICT: HEADLESS-DETECTOR (not CDP-discriminator) — both conditions show UA mismatch")
        print("  Both vanilla headless AND CDP-attached trigger the same finding.")
        print("  Useful for headless detection. Ship as Phase 1 finding if confirmed.")
        sys.exit(0)
    elif not all_match:
        print("\n  VERDICT: CDP-DISCRIMINATOR — different findings between conditions")
        print("  REJECT signal — could be a CDP attachment artifact, not a real bot signal.")
        sys.exit(1)
