from __future__ import annotations

import os
import threading
from pathlib import Path

import pytest

if os.getenv("STACKCHAIN_RUN_RELEASE_E2E") != "1":
    pytest.skip("packaged next-day Today handoff runs only in its gated CI job", allow_module_level=True)
pytest.importorskip("playwright.sync_api")
from playwright.sync_api import expect, sync_playwright

from fake_gitea import FakeGiteaServer
from test_mobile_offline_issue_release import ACCESS_TOKEN, ROOT, release_server


def test_release_artifact_reviews_wrap_up_commitments_on_a_phone(tmp_path: Path):
    archives = sorted((ROOT / "dist").glob("stackchain-dashboard-*.tar.gz"))
    assert len(archives) == 1
    fake = FakeGiteaServer(("127.0.0.1", 0))
    thread = threading.Thread(target=fake.serve_forever, daemon=True)
    thread.start()
    errors: list[str] = []
    try:
        with release_server(archives[0], tmp_path, f"http://127.0.0.1:{fake.server_port}") as origin, sync_playwright() as playwright:
            browser = playwright.chromium.launch(args=["--ignore-certificate-errors"])
            page = browser.new_page(viewport={"width": 390, "height": 844})
            page.on("pageerror", lambda error: errors.append(error.stack or str(error)))
            page.goto(origin + "/", wait_until="networkidle")
            page.locator('input[name="device_label"]').fill("Tomorrow review phone")
            page.locator('input[name="access_token"]').fill(ACCESS_TOKEN)
            page.locator("#submit-sign-in").click()
            page.wait_for_url(origin + "/", wait_until="networkidle")
            page.evaluate("""localStorage.setItem('stackchain.today-handoff.v1.timmy', JSON.stringify([
              'issue:acme/mobile:41:', 'issue:acme/mobile:42:'
            ]))""")
            page.reload(wait_until="networkidle")

            dialog = page.locator("#today-handoff-dialog")
            expect(dialog).to_be_visible()
            expect(page.locator("#today-handoff-items .today-handoff-item")).to_have_count(2)
            for control in dialog.locator("button, input").all():
                bounds = control.bounding_box()
                assert bounds and bounds["height"] >= 24
            buttons = dialog.locator("button")
            for control in buttons.all():
                bounds = control.bounding_box()
                assert bounds and bounds["height"] >= 44
            page.locator('[data-today-handoff="issue:acme/mobile:42:"]').uncheck()
            page.locator("#confirm-today-handoff").click()
            expect(dialog).to_be_hidden()
            assert page.evaluate("JSON.parse(localStorage.getItem('stackchain.today-work.v1.timmy'))") == [
                "issue:acme/mobile:41:"
            ]
            assert page.evaluate("JSON.parse(localStorage.getItem('stackchain.today-handoff.v1.timmy'))") == [
                "issue:acme/mobile:42:"
            ]
            assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth")
            assert errors == []
            browser.close()
    finally:
        fake.shutdown()
        fake.server_close()
        thread.join(timeout=5)
