#!/usr/bin/env python3
"""
Render pages with the system Chrome (headless, via Playwright) so the comparison
sees what's actually VISIBLE — both sites build content with JavaScript, so raw
HTML is not enough.

- Dev (brentwooddev.demoing.info) is behind the demoing gate; we authenticate once
  with the shared demoing password (low-value access gate, documented in CLAUDE.md;
  override with env DEMOING_GATE_PW) and reuse the cookie.
- Live (brentwood.ca) is public.
"""
import os
import requests
from playwright.sync_api import sync_playwright

GATE_PW = os.environ.get('DEMOING_GATE_PW', 'showmethesite')
_cookie = None

def gate_cookie():
    global _cookie
    if _cookie:                      # only cache a SUCCESSFUL login (empty string -> retry)
        return _cookie
    try:
        s = requests.Session()
        s.post('https://auth.demoing.info/auth/login', data={'password': GATE_PW}, timeout=15)
        _cookie = s.cookies.get('demoing_auth') or ''
    except Exception:
        _cookie = ''
    return _cookie

def _gated_out(html):
    """True if the demoing access gate served its login page instead of the real content."""
    return ('auth/login' in html or 'Remember this device' in html) and len(html) < 20000

def render_pair(dev_url, live_url, timeout=35000):
    """Render both URLs in one browser; return (dev_html, live_html)."""
    global _cookie
    with sync_playwright() as p:
        b = p.chromium.launch(channel='chrome', headless=True,
                              args=['--no-sandbox', '--disable-dev-shm-usage', '--disable-gpu'])
        ctx = b.new_context(viewport={'width': 1280, 'height': 2000})
        def apply_cookie():
            ck = gate_cookie()
            if ck:
                ctx.add_cookies([{'name': 'demoing_auth', 'value': ck, 'domain': '.demoing.info', 'path': '/'}])
        apply_cookie()
        def grab_once(u, wait):
            pg = ctx.new_page()
            try:
                pg.goto(u, wait_until=wait, timeout=timeout)
                pg.wait_for_timeout(700)   # settle late JS
                return pg.content()
            except Exception:
                try:
                    return pg.content()
                except Exception:
                    return ''
            finally:
                pg.close()
        def grab(u, gated):
            html, reauthed = '', False
            for attempt in range(4):       # transient DNS/net + gate-cookie failures -> retry
                html = grab_once(u, 'networkidle' if attempt == 0 else 'load')
                if gated and _gated_out(html) and not reauthed:
                    _cookie = None             # stale/missing gate cookie -> re-authenticate ONCE
                    apply_cookie()
                    reauthed = True            # never hammer the auth endpoint in a loop
                    continue
                if len(html) > 3000:
                    return html
            return html
        dev = grab(dev_url, gated=True)
        live = grab(live_url, gated=False)
        b.close()
    return dev, live
