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 Find Work 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_guides_mobile_find_work_through_assignment(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))
    fake.assigned_issue_numbers = []
    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] = []
    failed_responses: 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": 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("console", lambda message: browser_errors.append(message.text) if message.type == "error" else None)
            page.on(
                "response",
                lambda response: failed_responses.append(f"{response.status} {response.url}")
                if response.status >= 400
                else None,
            )

            page.goto(origin + "/", wait_until="networkidle")
            page.locator('input[name="device_label"]').fill("Find Work 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.locator('[data-mobile-task="find"]').click()
            expect(page.locator("#find-work-sheet")).to_have_class("find-work-sheet open")
            expect(page.locator(".find-work-card")).to_have_count(2)
            expect(page.locator("#find-work-status")).to_contain_text("2 of 2 available")

            navigation = page.locator(".mobile-find-work-nav")
            expect(navigation).to_be_visible()
            for control in navigation.locator("button").all():
                bounds = control.bounding_box()
                assert bounds and bounds["height"] >= 44
            assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth")

            page.locator("#select-find-work").click()
            choices = page.locator("[data-find-work-select]")
            expect(choices).to_have_count(2)
            choices.nth(0).check()
            choices.nth(1).check()
            page.locator("#claim-selected-work").click()

            expect(navigation.locator('[data-find-work-stage="review"]')).to_have_attribute(
                "aria-current", "step"
            )
            expect(page.locator("#find-work-review-list .find-work-review-item")).to_have_count(2)
            expect(page.locator("#find-work-review-summary")).to_contain_text("2 selected")
            page.locator("[data-find-work-review-remove]").nth(1).click()
            expect(page.locator("#find-work-review-list .find-work-review-item")).to_have_count(1)
            expect(page.locator("#find-work-review-summary")).to_contain_text("1 selected")

            page.locator("#continue-find-work-fit").click()
            expect(navigation.locator('[data-find-work-stage="fit"]')).to_have_attribute(
                "aria-current", "step"
            )
            expect(page.locator("#find-work-estimate-list")).to_contain_text("Ship mobile capture")
            for control in page.locator("#find-work-fit-stage button").all():
                bounds = control.bounding_box()
                assert bounds and bounds["height"] >= 44

            page.locator("#confirm-find-work-estimates").click()
            expect(navigation.locator('[data-find-work-stage="discover"]')).to_have_attribute(
                "aria-current", "step"
            )
            page.wait_for_timeout(1_000)
            status = page.locator("#find-work-status").inner_text()
            assert "1 queued" in status, {
                "status": status,
                "browser_errors": browser_errors,
                "failed_responses": failed_responses,
                "assigned": fake.assigned_issue_numbers,
                "today": page.evaluate("localStorage.getItem('stackchain.today-work.v1.timmy')"),
            }

            assert fake.assigned_issue_numbers == [41]
            today = page.evaluate("JSON.parse(localStorage.getItem('stackchain.today-work.v1.timmy') || '[]')")
            assert today == ["issue:acme/mobile:41:"]
            assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth")
            assert browser_errors == []
            assert failed_responses == []
            browser.close()
    finally:
        fake.shutdown()
        fake.server_close()
        fake_thread.join(timeout=5)
