"""Tests for web UI runtime health dashboard (#430)."""
import sys
import unittest
from pathlib import Path
from unittest import mock

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

from starlette.testclient import TestClient

from webui.app import create_app
from webui.runtime_health import _role_kind, load_runtime_snapshot, snapshot_to_dict


def _mock_identity(_host: str):
    return "jcwalker3", None


def _mock_git_sync(_repo: Path, _remote: str, _branch: str):
    return "localsha123456", "remoteshaabcdef", 2


class TestRuntimeHealthLoader(unittest.TestCase):
    def test_role_kind_author(self):
        allowed = ["gitea.pr.create", "gitea.branch.push", "gitea.read"]
        forbidden = ["gitea.pr.merge", "gitea.pr.approve"]
        self.assertEqual(_role_kind(allowed, forbidden), "author")

    def test_snapshot_with_mocks(self):
        snapshot = load_runtime_snapshot(
            resolve_username=_mock_identity,
            git_sync=_mock_git_sync,
        )
        self.assertEqual(snapshot.project_id, "gitea-tools")
        self.assertEqual(snapshot.authenticated_username, "jcwalker3")
        self.assertEqual(snapshot.commits_behind_master, 2)
        self.assertIsNotNone(snapshot.stale_runtime_warning)
        self.assertGreaterEqual(len(snapshot.workflow_hashes), 3)
        self.assertGreaterEqual(len(snapshot.schema_hashes), 2)
        self.assertIn("shell_use_allowed", snapshot.shell_health)

    def test_snapshot_dict_export(self):
        snapshot = load_runtime_snapshot(
            resolve_username=_mock_identity,
            git_sync=_mock_git_sync,
        )
        data = snapshot_to_dict(snapshot)
        self.assertEqual(data["authenticated_username"], "jcwalker3")
        self.assertEqual(data["commits_behind_master"], 2)
        self.assertTrue(data["stale_runtime_warning"])


class TestRuntimeRoutes(unittest.TestCase):
    def setUp(self):
        self.client = TestClient(create_app())
        self.snapshot = load_runtime_snapshot(
            resolve_username=_mock_identity,
            git_sync=_mock_git_sync,
        )
        self._patch = mock.patch(
            "webui.app.load_runtime_snapshot",
            return_value=self.snapshot,
        )
        self._patch.start()

    def tearDown(self):
        self._patch.stop()

    def test_runtime_page_renders_profile_and_warning(self):
        response = self.client.get("/runtime")
        self.assertEqual(response.status_code, 200)
        self.assertIn("Runtime health", response.text)
        self.assertIn("Active profile", response.text)
        self.assertIn("Stale runtime warning", response.text)
        self.assertIn("Workflow hashes", response.text)
        self.assertNotIn("child issue", response.text.lower())

    def test_api_runtime_json(self):
        response = self.client.get("/api/runtime")
        self.assertEqual(response.status_code, 200)
        data = response.json()
        self.assertEqual(data["project_id"], "gitea-tools")
        self.assertEqual(data["role_kind"], self.snapshot.role_kind)
        self.assertEqual(data["commits_behind_master"], 2)


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