#!/usr/bin/env python3
"""Real-browser checks for the lobby rules form (t1171/t1172).

- Dragging on the cease-fire clock paints and adjusts ranges smoothly (same
  SVG node throughout the drag; pointer capture survives polls).
- Typing in time / number inputs keeps focus across several poll cycles
  while other players join and leave (lobby version bumps).
- Non-hosts get a read-only form; the API refuses their rule edits (403).
- Times are shown in each player's local zone (host Amsterdam, guest Tokyo).
Desktop (mouse) and mobile (touch). Usage: python3 test/lobby-interaction-playwright.py [BASE]
"""
import math
import sys
from pathlib import Path
from urllib.parse import quote

from playwright.sync_api import sync_playwright

BASE = sys.argv[1] if len(sys.argv) > 1 else 'http://127.0.0.1:8080'
OUT = Path('/workspace/allianties-shots')
OUT.mkdir(parents=True, exist_ok=True)
FAILS = []


def check(cond, msg):
    print(('  ok  ' if cond else '  FAIL  ') + msg)
    if not cond:
        FAILS.append(msg)


def shot(page, name):
    page.screenshot(path=str(OUT / (name + '.png')), full_page=False)
    print('    shot', OUT / (name + '.png'))


def clock_point(page, minutes, radius_frac):
    box = page.locator('#cf-clock svg').bounding_box()
    scale = box['width'] / 320.0
    ang = minutes / 1440.0 * 2 * math.pi - math.pi / 2
    r = 128 * radius_frac * scale
    return (box['x'] + 160 * scale + r * math.cos(ang), box['y'] + 160 * scale + r * math.sin(ang))


def ranges(page):
    return page.evaluate("() => (App.game.rules.ceasefire_ranges || []).map(r => r.start + '-' + r.end)")


def mark_svg(page):
    page.evaluate("() => { window.__cfSvg = document.querySelector('#cf-clock svg'); }")


def same_svg(page):
    return page.evaluate("() => document.querySelector('#cf-clock svg') === window.__cfSvg")


def wait_saved(page):
    page.wait_for_function("() => !App.rulesDirty && !App._rulesSaving", timeout=10000)


def mouse_drag(page, m_from, m_to, frac, steps=16, poll_pause=False):
    x, y = clock_point(page, m_from, frac)
    page.mouse.move(x, y)
    page.mouse.down()
    ok = True
    span = (m_to - m_from) % 1440
    for i in range(1, steps + 1):
        m = (m_from + span * i / steps) % 1440
        px, py = clock_point(page, m, frac)
        page.mouse.move(px, py)
        page.wait_for_timeout(250 if poll_pause else 30)
        ok = ok and same_svg(page) and page.evaluate("() => App._cfClock.active()")
    page.mouse.up()
    return ok


def touch_drag(page, cdp, m_from, m_to, frac, steps=16, poll_pause=False):
    def tp(m):
        x, y = clock_point(page, m, frac)
        return [{'x': x, 'y': y, 'id': 1}]
    cdp.send('Input.dispatchTouchEvent', {'type': 'touchStart', 'touchPoints': tp(m_from)})
    ok = True
    span = (m_to - m_from) % 1440
    for i in range(1, steps + 1):
        m = (m_from + span * i / steps) % 1440
        cdp.send('Input.dispatchTouchEvent', {'type': 'touchMove', 'touchPoints': tp(m)})
        page.wait_for_timeout(250 if poll_pause else 30)
        ok = ok and same_svg(page) and page.evaluate("() => App._cfClock.active()")
    cdp.send('Input.dispatchTouchEvent', {'type': 'touchEnd', 'touchPoints': []})
    return ok


def churn(page3, code, times=1):
    """Another player joins and leaves: bumps the lobby version → host polls see a change."""
    for _ in range(times):
        page3.goto(BASE + '/index.html?join=' + code, wait_until='domcontentloaded')
        page3.wait_for_selector('#lobby:not([hidden])', timeout=10000)
        page3.locator('#btn-leave').click()
        page3.wait_for_timeout(300)


def type_slowly(page, sel, keys, churn_fn, label):
    page.locator(sel).focus()
    page.keyboard.press('Control+A')  # number input: replace; time input: first segment
    page.wait_for_timeout(100)
    kept = True
    for k in keys:
        if ':' in k:
            # Mobile browsers set a time input through the native picker,
            # not keystrokes: emulate that (value + input/change events).
            page.locator(sel).evaluate(
                "(el, v) => { el.value = v; el.dispatchEvent(new Event('input', {bubbles: true}));"
                " el.dispatchEvent(new Event('change', {bubbles: true})); }", k)
        else:
            page.keyboard.type(k)
        churn_fn()
        page.wait_for_timeout(1600)  # > one 3 s poll every two keys
        active = page.evaluate("(s) => document.activeElement === document.querySelector(s)", sel)
        kept = kept and active
    check(kept, label + ': focus kept across polls while others join/leave')
    print('    value after typing:', page.locator(sel).input_value())
    return kept


def run(p, mobile):
    tag = 'mobile' if mobile else 'desktop'
    print('== ' + tag)
    browser = p.chromium.launch()
    if mobile:
        ctx_opts = dict(viewport={'width': 390, 'height': 844}, device_scale_factor=2, is_mobile=True, has_touch=True)
    else:
        ctx_opts = dict(viewport={'width': 1280, 'height': 900})
    host_ctx = browser.new_context(locale='en-GB', timezone_id='Europe/Amsterdam', **ctx_opts)
    guest_ctx = browser.new_context(locale='en-GB', timezone_id='Asia/Tokyo', **ctx_opts)
    churn_ctx = browser.new_context(locale='en-GB', timezone_id='UTC')
    page = host_ctx.new_page()
    page.goto(BASE + '/auth.php?test=1', wait_until='networkidle')
    page.wait_for_selector('#btn-create')
    check('paranoia' in page.locator('.tagline').first.inner_text(), 'new tagline shown')
    page.locator('#btn-create').click()
    page.wait_for_selector('#lobby:not([hidden])')
    code = page.locator('#lobby-code').inner_text().strip()
    check(page.evaluate("() => App.game.rules.tz") == 'Europe/Amsterdam', 'lobby created with host zone')

    guest = guest_ctx.new_page()
    guest.goto(BASE + '/auth.php?test=2&next=' + quote('index.html?join=' + code, safe=''), wait_until='networkidle')
    guest.wait_for_selector('#lobby:not([hidden])')
    page3 = churn_ctx.new_page()
    page3.goto(BASE + '/auth.php?test=3', wait_until='networkidle')

    page.locator('#rule-ceasefire').check()
    page.wait_for_selector('#ceasefire-editor:not([hidden])')
    page.locator('#cf-clock').scroll_into_view_if_needed()
    wait_saved(page)
    mark_svg(page)

    # 1. Paint 10:00 → 14:00 on the ring, slowly (so polls happen mid-drag).
    cdp = host_ctx.new_cdp_session(page) if mobile else None
    if mobile:
        smooth = touch_drag(page, cdp, 600, 840, 0.8, steps=16, poll_pause=True)
    else:
        churn(page3, code)
        smooth = mouse_drag(page, 600, 840, 0.8, steps=16, poll_pause=True)
    check(smooth, 'paint drag: same SVG node and active drag on every move (%s)' % tag)
    wait_saved(page)
    check('10:00-14:00' in ranges(page), 'painted 10:00-14:00: %s' % ranges(page))
    shot(page, tag + '-clock-painted')

    # 2. Drag the end handle 14:00 → 16:00.
    if mobile:
        smooth = touch_drag(page, cdp, 840, 960, 1.0, steps=8)
    else:
        smooth = mouse_drag(page, 840, 960, 1.0, steps=8)
    check(smooth, 'handle drag smooth (%s)' % tag)
    wait_saved(page)
    check(ranges(page) == ['10:00-16:00'], 'handle moved end to 16:00: %s' % ranges(page))
    rows = page.evaluate("() => [...document.querySelectorAll('#cf-ranges li.cf-row input')].map(i => i.value)")
    check(rows == ['10:00', '16:00'], 'time inputs follow the clock: %s' % rows)
    # Snap: a drag that ends near 16:07 lands on 16:00 (15-minute grid).
    page.wait_for_timeout(3500)
    check(same_svg(page), 'clock SVG survives polls (patched in place)')

    # 3. Typing keeps focus across polls (others join/leave meanwhile).
    page.locator('#rule-ap-time').scroll_into_view_if_needed()
    type_slowly(page, '#rule-ap-time', ['07:00', '07:15', '07:30'] if mobile else ['0', '7', '3', '0'],
                lambda: churn(page3, code), 'AP time input')
    page.locator('#lobby h1').click()
    wait_saved(page)
    page.wait_for_timeout(500)
    check(page.evaluate("() => App.game.rules.ap_time") == '07:30', 'AP time saved 07:30')
    shot(page, tag + '-lobby-host-edit')

    page.locator('#cf-ranges li.cf-row input').first.scroll_into_view_if_needed()
    type_slowly(page, '#cf-ranges li.cf-row input.cf-start', ['09:00', '09:30', '09:45'] if mobile else ['0', '9', '4', '5'],
                lambda: churn(page3, code), 'cease-fire start input')
    page.locator('#lobby h1').click()
    wait_saved(page)
    page.wait_for_timeout(500)
    check(ranges(page) == ['09:45-16:00'], 'typed start saved: %s' % ranges(page))

    type_slowly(page, '#rule-grid', ['1', '2'], lambda: churn(page3, code), 'grid size input')
    page.locator('#lobby h1').click()
    wait_saved(page)
    check(page.evaluate("() => App.game.rules.grid") == 12, 'grid 12 saved')

    # 4. Guest (Tokyo): read-only, converted to local time, API refuses (403).
    guest.wait_for_timeout(3500)
    guest.locator('#lobby-rules').scroll_into_view_if_needed()
    check(guest.locator('#rules-host-only').is_visible(), 'guest sees "Only the host can change the rules."')
    disabled = guest.evaluate("() => [...document.querySelectorAll('#lobby-rules input, #lobby-rules button')].every(e => e.disabled)")
    check(disabled, 'guest: every rules input/button disabled')
    g_ap = guest.locator('#rule-ap-time').input_value()
    check(g_ap == '15:30', 'guest in Tokyo sees AP time 07:30 Amsterdam as 15:30: %s' % g_ap)
    g_rows = guest.evaluate("() => [...document.querySelectorAll('#cf-ranges li.cf-row input')].map(i => i.value)")
    check(g_rows == ['17:45', '00:00'], 'guest sees 09:45–16:00 Amsterdam as 17:45–00:00 Tokyo: %s' % g_rows)
    check('Asia/Tokyo' in guest.locator('.tz-label').first.inner_text(), 'guest zone label: ' + guest.locator('.tz-label').first.inner_text())
    status = guest.evaluate("""async () => {
        const r = await fetch('api.php?action=lobby_rules', { method: 'POST', credentials: 'same-origin',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': Api.csrf },
            body: JSON.stringify({ action: 'lobby_rules', game: App.game.id, rules: { jury: false } }) });
        const d = await r.json();
        return [r.status, d.error];
    }""")
    check(status == [403, 'not_host'], 'guest rule update refused with 403 not_host: %s' % status)
    page.wait_for_timeout(3500)
    check(page.evaluate("() => App.game.rules.jury") is True, 'rules unchanged after refused guest edit')
    guest.locator('#ceasefire-editor').scroll_into_view_if_needed()
    shot(guest, tag + '-lobby-guest-readonly-tokyo')
    page.locator('#ceasefire-editor').scroll_into_view_if_needed()
    shot(page, tag + '-lobby-host-clock')
    browser.close()


with sync_playwright() as p:
    run(p, mobile=False)
    run(p, mobile=True)

print('\nFAILED: %d' % len(FAILS))
for f in FAILS:
    print(' - ' + f)
sys.exit(1 if FAILS else 0)
