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 Today wrap-up journey 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


@pytest.mark.parametrize(("width", "height"), [(320, 568), (390, 844)])
def test_release_artifact_renders_and_applies_mobile_today_wrap_up(
    tmp_path: Path, width: int, height: int
):
    archives = sorted((ROOT / "dist").glob("stackchain-dashboard-*.tar.gz"))
    assert len(archives) == 1, "browser job must download exactly one assembled release archive"

    fake = FakeGiteaServer(("127.0.0.1", 0))
    fake_thread = threading.Thread(target=fake.serve_forever, daemon=True)
    fake_thread.start()
    fake_url = f"http://127.0.0.1:{fake.server_port}"
    browser_errors: list[str] = []

    try:
        with release_server(archives[0], tmp_path, fake_url) as origin, sync_playwright() as playwright:
            browser = playwright.chromium.launch(args=["--ignore-certificate-errors"])
            context = browser.new_context(
                viewport={"width": width, "height": height}, ignore_https_errors=True
            )
            page = context.new_page()
            page.on("pageerror", lambda error: browser_errors.append(error.stack or str(error)))
            page.on(
                "console",
                lambda message: browser_errors.append(message.text)
                if message.type == "error"
                else None,
            )
            page.goto(origin + "/", wait_until="networkidle")
            page.locator('input[name="device_label"]').fill("Today wrap-up release 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(
                """
                () => {
                  const items=[
                    {kind:'issue',repository:'acme/mobile',number:41,title:'Ship mobile capture',key:'acme/mobile#41'},
                    {kind:'issue',repository:'acme/mobile',number:42,title:'Polish desktop filters',key:'acme/mobile#42'},
                  ];
                  const identity=item => `${item.kind}:${item.repository}:${item.number}:`;
                  const today=items.map(identity); const operations=[];
                  let tomorrow={revision:4,ids:['issue:acme/mobile:42:'],capacity_minutes:120,
                    estimates:{'issue:acme/mobile:42:':45},plan_date:'2026-08-18'};
                  const todayWork={identity,read:()=>[...today],contains:item=>today.includes(identity(item)),remove:item=>{
                    const index=today.indexOf(identity(item)); if(index<0)return false; today.splice(index,1); return true;
                  }};
                  const tomorrowPlan={load:async()=>tomorrow,stage:value=>{
                    tomorrow={...tomorrow,...value,sync_pending:true}; return tomorrow;
                  }};
                  const todaySync={enqueue:(action,id)=>{operations.push([action,id]);return true;},flush:()=>Promise.resolve(true)};
                  const controller=createTodayWrapUp({todayWork,tomorrowPlan,todaySync});
                  const view=createTodayWrapUpView({controller,qs:selector=>document.querySelector(selector),escapeHtml:value=>String(value)});
                  window.__wrapTest={view,today,getTomorrow:()=>tomorrow,operations};
                  view.open(items,{});
                }
                """
            )

            sheet = page.locator("#today-wrap-up-sheet")
            expect(sheet).to_be_visible()
            expect(page.locator(".today-wrap-up-item")).to_have_count(2)
            for control in sheet.locator("button, label").all():
                bounds = control.bounding_box()
                assert bounds and bounds["height"] >= 44
            assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth")

            page.locator('[data-wrap-up-identity="issue:acme/mobile:41:"]').check()
            page.evaluate("window.__wrapTest.view.finish(document.querySelector('#finish-today-wrap-up'))")
            expect(sheet).to_be_hidden()
            result = page.evaluate(
                "({today:window.__wrapTest.today,tomorrow:window.__wrapTest.getTomorrow(),operations:window.__wrapTest.operations})"
            )
            assert result == {
                "today": ["issue:acme/mobile:42:"],
                "tomorrow": {
                    "revision": 4,
                    "ids": ["issue:acme/mobile:42:", "issue:acme/mobile:41:"],
                    "capacity_minutes": 120,
                    "estimates": {"issue:acme/mobile:42:": 45},
                    "plan_date": "2026-08-18",
                    "sync_pending": True,
                },
                "operations": [["remove", "issue:acme/mobile:41:"]],
            }
            assert browser_errors == []
            browser.close()
    finally:
        fake.shutdown()
        fake.server_close()
        fake_thread.join(timeout=5)
