#!/usr/bin/env python3
"""
emoji-os 2-test validation
- Vanilla Playwright (no CDP)
- CDP-attached Chrome

Detects: UA claims Mac/Windows but emoji render as Tofu/fallback (no color emoji fonts).
This happens on Linux headless without fonts-noto-color-emoji installed.
"""
import sys
from playwright.sync_api import sync_playwright

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

def run(condition, attach_cdp=False):
    print(f"\n=== {condition.upper()} ===")
    with sync_playwright() as p:
        args = ["--no-sandbox"]
        if attach_cdp:
            browser = p.chromium.launch(
                headless=True,
                args=args + ["--remote-debugging-port=9224"],
            )
        else:
            browser = p.chromium.launch(headless=True, args=args)

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

        if attach_cdp:
            cdp = ctx.new_cdp_session(page)
            cdp.send("Runtime.enable")

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

        print(f"  navPlatform:    {result['navPlatform']}")
        print(f"  uaDataPlatform: {result['uaDataPlatform']}")
        print(f"  claimsApple:    {result['claimsApple']}")
        print(f"  claimsWindows:  {result['claimsWindows']}")
        print(f"  colorRatio:     {result['colorRatio']*100:.0f}%")
        print(f"  tofuRenders:    {result['tofuRenders']} / {result['totalRenders']}")
        print(f"  appleLie:       {result['appleLie']}")
        print(f"  windowsLie:     {result['windowsLie']}")
        print(f"  emojiFallback:  {result['emojiFallback']}")

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

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

    print("\n=== COMPARISON ===")
    v = RESULTS["vanilla"]
    c = RESULTS["cdp"]
    all_match = all([
        v["claimsApple"] == c["claimsApple"],
        v["claimsWindows"] == c["claimsWindows"],
        v["colorRatio"] == c["colorRatio"],
        v["tofuRenders"] == c["tofuRenders"],
        v["appleLie"] == c["appleLie"],
        v["windowsLie"] == c["windowsLie"],
    ])
    print(f"  All checks identical across conditions: {all_match}")
    print(f"  Vanilla: colorRatio={v['colorRatio']*100:.0f}%, appleLie={v['appleLie']}, windowsLie={v['windowsLie']}")
    print(f"  CDP:     colorRatio={c['colorRatio']*100:.0f}%, appleLie={c['appleLie']}, windowsLie={c['windowsLie']}")

    # Verdict logic
    if not v["claimsApple"] and not v["claimsWindows"]:
        print("\n  Baseline check: env claims Linux (no Apple/Windows UA).")
        print(f"  Color ratio = {v['colorRatio']*100:.0f}% on Linux headless.")

    if all_match and v["colorRatio"] < 0.5:
        print("\n  VERDICT: HEADLESS-DETECTOR — emoji fonts missing in both conditions")
        print("  Useful for headless detection. Ship as Phase 1 finding.")
        sys.exit(0)
    elif all_match and v["colorRatio"] >= 0.5:
        print("\n  VERDICT: NO SIGNAL — env has color emoji fonts, no fallback")
        print("  Cannot detect from emoji alone in this env.")
        sys.exit(0)
    elif not all_match:
        print("\n  VERDICT: CDP-DISCRIMINATOR — different emoji behavior between conditions")
        print("  REJECT signal.")
        sys.exit(1)
