#!/usr/bin/env python3
"""Desktop + mobile screenshots and a two-player local flow."""
from __future__ import annotations

import sys
from pathlib import Path
from urllib.parse import quote

from playwright.sync_api import sync_playwright, expect

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


def shot(page, name, full=False):
    path = SHOTS / f'{name}.png'
    page.screenshot(path=str(path), full_page=full)
    print('shot', path)


def shot_full(page, name):
    shot(page, name, full=True)


def main():
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=True)
        desk = browser.new_context(viewport={'width': 1280, 'height': 800}, locale='en-GB')
        page = desk.new_page()
        page.goto(BASE + '/', wait_until='networkidle')
        page.wait_for_selector('#menu h1')
        expect(page.locator('#menu h1')).to_have_text('Allianties')
        shot_full(page, 'desktop-menu-guest')

        # Flag picker
        page.locator('#lang-current').click()
        page.wait_for_selector('#lang-list:not([hidden])')
        shot(page, 'desktop-lang-picker')
        page.locator('#lang-current').click()  # close, stay in English
        page.wait_for_timeout(200)

        # Login test user 1
        page.goto(BASE + '/auth.php?test=1', wait_until='networkidle')
        page.wait_for_selector('#btn-create')
        shot_full(page, 'desktop-menu-loggedin')

        page.locator('#btn-create').click()
        page.wait_for_selector('#lobby:not([hidden])')
        page.wait_for_timeout(200)
        shot_full(page, 'desktop-lobby')

        # Enable shrink, AP loot, cease-fire, set AP time, show clock + vis options
        page.locator('#rule-shrink').check()
        page.locator('#rule-ap-loot').check()
        page.locator('#rule-ap-time').fill('00:00')
        page.locator('#rule-ceasefire').check()
        page.wait_for_selector('#ceasefire-editor:not([hidden])')
        page.wait_for_timeout(200)
        shot_full(page, 'desktop-lobby-rules-clock')

        page.locator('#cf-add').click()
        page.wait_for_timeout(300)
        # Use a daytime range so we can still shoot later (not wrapping current night)
        # Fill via evaluate so locale 12h inputs don't bite.
        page.evaluate("""() => {
            const inputs = document.querySelectorAll('#cf-ranges input[type=time]');
            if (inputs[0]) inputs[0].value = '10:00';
            if (inputs[1]) inputs[1].value = '12:00';
            inputs[0] && inputs[0].dispatchEvent(new Event('change', { bubbles: true }));
        }""")
        page.wait_for_timeout(400)
        shot_full(page, 'desktop-lobby-cf-range')
        shot_full(page, 'desktop-lobby-options')  # time picker, loot, vis, clock

        # Scroll visibility into view
        vis = page.locator('#lobby-visibility')
        if vis.count():
            vis.scroll_into_view_if_needed()
            page.wait_for_timeout(150)
            shot(page, 'desktop-lobby-visibility')

        code = page.locator('#lobby-code').inner_text().strip()
        print('lobby code', code)

        # Turn cease-fire OFF before start so shots are legal; keep the other options.
        # (Clock already screenshotted.) 10:00-12:00 is already off at night, fine.

        desk2 = browser.new_context(viewport={'width': 1280, 'height': 800}, locale='en-GB')
        page2 = desk2.new_page()
        next_url = quote('index.html?join=' + code, safe='')
        page2.goto(BASE + '/auth.php?test=2&next=' + next_url, wait_until='networkidle')
        print('player2 url', page2.url)
        try:
            page2.wait_for_selector('#lobby:not([hidden]), #game:not([hidden])', timeout=15000)
        except Exception:
            shot(page2, 'debug-player2')
            print('player2 text', page2.locator('body').inner_text()[:800])
            raise
        page2.wait_for_timeout(300)
        shot_full(page2, 'desktop-player2-lobby')

        page.wait_for_function(
            "() => document.querySelectorAll('#lobby-players li').length >= 2",
            timeout=15000,
        )
        shot_full(page, 'desktop-lobby-two-players')
        page.locator('#btn-start').click()
        page.wait_for_selector('#game:not([hidden])')
        page.wait_for_timeout(400)
        expect(page.locator('#ap-hms')).to_be_visible()
        shot(page, 'desktop-game')

        # Click own tank, screenshot selection + move targets + timeline controls
        pieces = page.locator('#board .cell:has(.piece, .piece-initials)')
        print('pieces', pieces.count())
        if pieces.count() >= 1:
            pieces.nth(0).click()
            page.wait_for_timeout(250)
            shot(page, 'desktop-game-selected')
            # Move toward the other player if a move-target exists
            targets = page.locator('#board .cell.move-target')
            if targets.count() >= 1:
                # Prefer a cell closer to the bottom (higher y) — downward toward P2
                targets.last.click()
                page.wait_for_timeout(500)
                shot(page, 'desktop-game-moved')

        # Player 2: after poll, should see the move; in range now, can give / attack
        page2.wait_for_timeout(3500)
        # If still lobby, start already happened — poll should switch to game
        if page2.locator('#lobby:not([hidden])').count():
            page2.wait_for_selector('#game:not([hidden])', timeout=10000)
        page2.wait_for_selector('#game:not([hidden])', timeout=10000)
        page2.wait_for_timeout(300)
        shot(page2, 'desktop-game-p2')

        # Click the opponent (T1, first or the non-own piece)
        def click_opponent(pg):
            cells = pg.locator('#board .cell:has(.piece, .piece-initials)')
            n = cells.count()
            # Click each until the sheet opens
            for i in range(n):
                cells.nth(i).click()
                pg.wait_for_timeout(200)
                if pg.locator('#sheet:not([hidden])').count():
                    return True
            return False

        if click_opponent(page2):
            shot(page2, 'desktop-player-menu')
            # Info
            page2.locator('#sheet-body button').first.click()
            page2.wait_for_selector('#modal:not([hidden])')
            page2.wait_for_timeout(200)
            shot(page2, 'desktop-info')
            page2.locator('#modal-close').click()
            page2.wait_for_timeout(150)

        if click_opponent(page2):
            # Give AP — the Give button is usually 3rd (Info, Attack, Give, Message)
            btns = page2.locator('#sheet-body button')
            give = None
            for i in range(btns.count()):
                t = btns.nth(i).inner_text()
                if 'Give' in t or 'geven' in t.lower() or 'AP' in t:
                    give = btns.nth(i)
                    break
            if give is None and btns.count() >= 3:
                give = btns.nth(2)
            if give is not None and give.is_disabled():
                # Opponent out of range (random spawn): giving is legitimately disabled.
                print('give disabled (out of range), skipping')
                page2.locator('#sheet-close').click()
                page2.wait_for_timeout(150)
                give = None
            if give is not None:
                give.click()
                page2.wait_for_selector('#modal:not([hidden])')
                page2.wait_for_timeout(200)
                shot(page2, 'desktop-give-ap')
                # Actually send 1 AP so we get a green arrow in playback
                send = page2.locator('#modal-body button').last
                if not send.is_disabled():
                    send.click()
                    page2.wait_for_timeout(600)
                else:
                    page2.locator('#modal-close').click()

        # Chat
        if click_opponent(page2):
            btns = page2.locator('#sheet-body button')
            chat = None
            for i in range(btns.count()):
                t = btns.nth(i).inner_text()
                if 'message' in t.lower() or 'bericht' in t.lower() or 'chat' in t.lower():
                    chat = btns.nth(i)
                    break
            if chat is None and btns.count() >= 4:
                chat = btns.nth(3)
            if chat is not None:
                chat.click()
                page2.wait_for_selector('#modal:not([hidden])')
                page2.wait_for_timeout(200)
                # type a message
                inp = page2.locator('#modal-body input[type="text"]')
                if inp.count():
                    inp.fill('Good luck!')
                shot(page2, 'desktop-chat')
                form_btn = page2.locator('#modal-body button[type="submit"]')
                if form_btn.count():
                    form_btn.click()
                    page2.wait_for_timeout(400)
                    shot(page2, 'desktop-chat-sent')
                page2.locator('#modal-close').click()

        # Advance a day on player 1 so they have AP again, then shoot (red arrow)
        page.evaluate("""async () => {
            if (window.Api && App.game) {
                try { await Api.debugAdvance(App.game.id, 1); await App.refreshFull(); }
                catch (e) { console.error(e); }
            }
        }""")
        page.wait_for_timeout(500)
        if click_opponent(page):
            btns = page.locator('#sheet-body button')
            atk = None
            for i in range(btns.count()):
                t = btns.nth(i).inner_text()
                if 'Attack' in t or 'Aanval' in t or 'Shoot' in t or 'schiet' in t.lower():
                    atk = btns.nth(i)
                    break
            if atk is None and btns.count() >= 2:
                atk = btns.nth(1)
            if atk is not None and not atk.is_disabled():
                atk.click()
                page.wait_for_timeout(500)
                shot(page, 'desktop-game-after-shot')

        # Close any sheet left open (e.g. attack disabled when out of range)
        if page.locator('#sheet:not([hidden])').count():
            page.locator('#sheet-close').click()
            page.wait_for_timeout(150)

        # Playback arrows: rewind and play
        if page.locator('#tl-back').count():
            # Jump to start via stepping back many times, then play
            for _ in range(8):
                page.locator('#tl-back').click()
                page.wait_for_timeout(80)
            shot(page, 'desktop-timeline-start')
            page.locator('#tl-play').click()
            # Mid-playback: wait enough for a give/shoot/move arrow to show
            page.wait_for_timeout(700)
            shot(page, 'desktop-playback-arrows')
            page.wait_for_timeout(900)
            shot(page, 'desktop-playback-arrows-2')
            # Pause, step forward, jump to present
            if page.locator('#tl-play').get_attribute('title') and 'Pause' in (page.locator('#tl-play').get_attribute('title') or ''):
                page.locator('#tl-play').click()
            page.locator('#tl-fwd').click()
            page.wait_for_timeout(200)
            shot(page, 'desktop-timeline-step')
            page.locator('#tl-live').click()
            page.wait_for_timeout(200)
            shot(page, 'desktop-timeline-live')

        # Settings / surrender (don't confirm)
        page.locator('#btn-settings').click()
        page.wait_for_selector('#settings-panel:not([hidden])')
        shot(page, 'desktop-settings')
        page.locator('#btn-surrender').click()
        page.wait_for_selector('#modal:not([hidden])')
        shot(page, 'desktop-surrender-confirm')
        page.locator('#modal-close').click()

        # --- Mobile ---
        mobile = browser.new_context(
            viewport={'width': 390, 'height': 844},
            is_mobile=True,
            has_touch=True,
            user_agent='Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1',
            locale='en-GB',
        )
        mp = mobile.new_page()
        mp.goto(BASE + '/', wait_until='networkidle')
        shot(mp, 'mobile-menu-guest')
        mp.locator('#lang-current').click()
        mp.wait_for_selector('#lang-list:not([hidden])')
        shot(mp, 'mobile-lang-picker')

        mp.goto(BASE + '/auth.php?test=3', wait_until='networkidle')
        mp.wait_for_selector('#btn-create, #menu-user')
        shot(mp, 'mobile-menu')
        mp.locator('#btn-create').click()
        mp.wait_for_selector('#lobby:not([hidden])')
        mp.locator('#rule-ceasefire').check()
        mp.locator('#rule-ap-loot').wait_for()
        mp.wait_for_timeout(300)
        shot_full(mp, 'mobile-lobby-clock')
        mp.locator('#rule-ap-time').scroll_into_view_if_needed()
        shot(mp, 'mobile-lobby-ap-time')
        vis = mp.locator('#lobby-visibility')
        if vis.count():
            vis.scroll_into_view_if_needed()
            shot(mp, 'mobile-lobby-visibility')

        # Player 2's running game on mobile
        mobile2 = browser.new_context(
            viewport={'width': 390, 'height': 844},
            is_mobile=True,
            has_touch=True,
            locale='en-GB',
        )
        m2 = mobile2.new_page()
        m2.goto(BASE + '/auth.php?test=2', wait_until='networkidle')
        m2.wait_for_selector('#menu, #game, #lobby')
        if m2.locator('#games-list button').count() > 0:
            m2.locator('#games-list button').first.click()
            m2.wait_for_selector('#game:not([hidden]), #lobby:not([hidden])')
            m2.wait_for_timeout(400)
            shot(m2, 'mobile-game')
            if m2.locator('#ap-hms').count():
                shot(m2, 'mobile-game-countdown')
            # playback on mobile
            if m2.locator('#tl-play').count() and m2.locator('#game:not([hidden])').count():
                m2.locator('#tl-back').click()
                m2.locator('#tl-back').click()
                m2.locator('#tl-play').click()
                m2.wait_for_timeout(700)
                shot(m2, 'mobile-playback-arrows')

        desk.close()
        desk2.close()
        mobile.close()
        mobile2.close()
        browser.close()
    print('playwright done')


if __name__ == '__main__':
    main()
