import json
import subprocess
import unittest
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]


def source(path: str) -> str:
    return (ROOT / path).read_text(encoding="utf-8")


def maybe_source(path: str) -> str:
    file_path = ROOT / path
    if not file_path.exists():
        return ""
    return file_path.read_text(encoding="utf-8")


class FrontendAccessContractTests(unittest.TestCase):
    def test_frontend_tracks_permissions_and_route_access(self):
        auth = source("frontend/src/stores/auth.js")
        router = source("frontend/src/router/index.js")
        access = maybe_source("frontend/src/utils/access.js")

        self.assertIn("permissions", auth)
        self.assertIn("allowedRoutes", auth)
        self.assertIn("hasRouteAllowlist", auth)
        self.assertIn("meta: { requiresAuth: true, routeAccess:", router)
        self.assertIn("router.getRoutes()", router)
        self.assertIn("route.meta?.permission", router)
        self.assertIn("route.meta?.routeAccess", router)
        self.assertIn("export function hasPermission", access)
        self.assertIn("export function canAccessRoute", access)
        self.assertIn("export function hasRouteAllowlist", access)

    def test_access_helper_behaves_like_route_whitelist(self):
        access_module_uri = (ROOT / "frontend/src/utils/access.js").as_uri()
        node_source = f"""
import("{access_module_uri}").then((mod) => {{
  const result = {{
    unrestricted: mod.hasRouteAllowlist({{ allowed_routes: [] }}),
    denied: mod.canAccessRoute({{ allowed_routes: [] }}, "Customers"),
    allowed: mod.canAccessRoute({{ allowed_routes: ["Customers"] }}, "Customers"),
  }}
  process.stdout.write(JSON.stringify(result))
}})
"""
        completed = subprocess.run(
            ["node", "--input-type=module", "-e", node_source],
            check=True,
            capture_output=True,
            text=True,
        )
        payload = json.loads(completed.stdout)
        self.assertFalse(payload["unrestricted"])
        self.assertFalse(payload["denied"])
        self.assertTrue(payload["allowed"])

    def test_dashboard_shows_current_month_income_not_total_revenue(self):
        dashboard = source("frontend/src/pages/DashboardPage.vue")

        self.assertIn("本月收入", dashboard)
        self.assertIn("currentMonthRevenue", dashboard)
        self.assertNotIn("overview.total_revenue", dashboard)
        self.assertNotIn(">总收入<", dashboard)


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