"""Tests for web UI CI path-filter gate (#436)."""
import os
import subprocess
import sys
import unittest
from pathlib import Path
from unittest import mock

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

from webui.ci_paths import should_run_webui_ci, touches_webui_surface
from webui.lease_loader import load_lease_snapshot
from webui.queue_loader import load_queue_snapshot
from webui.runtime_health import load_runtime_snapshot

_REPO_ROOT = Path(__file__).resolve().parent.parent


class TestCiPathMatching(unittest.TestCase):
    def test_positive_paths(self):
        for path in (
            "webui/app.py",
            "tests/test_webui_skeleton.py",
            "docs/webui-local-dev.md",
            "scripts/test-webui",
        ):
            with self.subTest(path=path):
                self.assertTrue(touches_webui_surface(path))

    def test_negative_paths(self):
        for path in ("mcp_server.py", "tests/test_mcp_server.py", "README.md"):
            with self.subTest(path=path):
                self.assertFalse(touches_webui_surface(path))

    def test_should_run_aggregate(self):
        self.assertTrue(should_run_webui_ci(["README.md", "webui/layout.py"]))
        self.assertFalse(should_run_webui_ci(["mcp_server.py", "gitea_auth.py"]))


class TestCiRunnerScript(unittest.TestCase):
    def test_test_webui_smoke(self):
        script = _REPO_ROOT / "scripts" / "test-webui"
        result = subprocess.run(
            ["bash", str(script), "-q"],
            cwd=_REPO_ROOT,
            capture_output=True,
            text=True,
            timeout=60,
            env={
                **os.environ,
                "WEBUI_TEST_PATTERN": "test_webui_skeleton.py",
            },
        )
        self.assertEqual(result.returncode, 0, result.stderr or result.stdout)


class TestOfflineWebuiCiMode(unittest.TestCase):
    def test_offline_mode_avoids_live_queue_auth(self):
        with mock.patch.dict(os.environ, {"WEBUI_TEST_OFFLINE": "1"}):
            with mock.patch(
                "webui.queue_loader.get_auth_header",
                side_effect=AssertionError("live auth should not run"),
            ):
                snapshot = load_queue_snapshot()
        self.assertIsNone(snapshot.fetch_error)
        self.assertEqual(snapshot.prs, ())
        self.assertEqual(snapshot.issues, ())

    def test_offline_mode_avoids_live_lease_auth(self):
        with mock.patch.dict(os.environ, {"WEBUI_TEST_OFFLINE": "1"}):
            with mock.patch(
                "webui.lease_loader.get_auth_header",
                side_effect=AssertionError("live auth should not run"),
            ):
                snapshot = load_lease_snapshot()
        self.assertIsNone(snapshot.fetch_error)
        self.assertEqual(snapshot.reviewer_leases, ())

    def test_offline_mode_avoids_live_runtime_identity(self):
        with mock.patch.dict(os.environ, {"WEBUI_TEST_OFFLINE": "1"}):
            with mock.patch(
                "webui.runtime_health.get_auth_header",
                side_effect=AssertionError("live auth should not run"),
            ):
                snapshot = load_runtime_snapshot()
        self.assertEqual(snapshot.identity_error, "offline web UI test mode")


if __name__ == "__main__":
    unittest.main()
