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 mobile sign-out 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


def test_release_artifact_reviews_private_work_before_mobile_sign_out(tmp_path: Path):
    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))
    thread = threading.Thread(target=fake.serve_forever, daemon=True)
    thread.start()
    delete_requests: list[str] = []
    browser_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"])
            context = browser.new_context(
                viewport={"width": 390, "height": 844}, ignore_https_errors=True
            )
            page = context.new_page()
            page.on("pageerror", lambda error: browser_errors.append(error.stack or str(error)))
            page.on(
                "request",
                lambda request: delete_requests.append(request.url)
                if request.method == "DELETE" and "/api/v1/session" in request.url
                else None,
            )
            page.goto(origin + "/", wait_until="networkidle")
            page.locator('input[name="device_label"]').fill("Sign-out 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.release-test-draft', 'unsynced')")

            launcher = page.locator("#sign-out")
            page.locator("#app-menu-toggle").click()
            launcher.click()
            sheet = page.locator("#sign-out-review-sheet")
            expect(sheet).to_be_visible()
            expect(page.locator("#sign-out-review-summary")).to_contain_text("private browser item")
            expect(page.locator("#sign-out-review-warning")).to_contain_text("may not be synced")
            expect(page.locator("#confirm-sign-out")).to_have_text("Sign out and erase private work")
            assert page.evaluate("document.querySelector('main').inert") is True
            panel = page.locator(".sign-out-review-panel").bounding_box()
            assert panel and panel["height"] <= 844
            for selector in ("#cancel-sign-out", "#confirm-sign-out"):
                bounds = page.locator(selector).bounding_box()
                assert bounds and bounds["height"] >= 44
            assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth")
            assert delete_requests == []

            page.keyboard.press("Escape")
            expect(sheet).to_be_hidden()
            expect(launcher).to_be_focused()
            assert page.evaluate("document.querySelector('main').inert") is False
            assert page.evaluate("localStorage.getItem('stackchain.release-test-draft')") == "unsynced"
            assert delete_requests == []
            assert browser_errors == []
            browser.close()
    finally:
        fake.shutdown()
        fake.server_close()
        thread.join(timeout=5)
