from __future__ import annotations

import json
import tempfile
import unittest
from pathlib import Path

from account_registry import AccountRegistry
from health_client import AccountSnapshot, HealthStatus
from routing_resolver import NoHealthyAccountError, RoutingResolver, load_rules


class AccountRoutingDesignTest(unittest.TestCase):
    def test_v1_rules_migrate_and_dynamic_resolves(self) -> None:
        with tempfile.TemporaryDirectory() as directory:
            path = Path(directory) / "routing_rules.json"
            path.write_text(json.dumps({"projects": {"repo": "avi"}, "default": "dynamic", "fallback_chain": [], "fallback_trigger": "broken_only", "quota_exhausted_threshold_pct": 100}))
            rules = load_rules(path)
            snapshot = AccountSnapshot(HealthStatus.OK, 0, 0)
            route = RoutingResolver(rules, {"avi": snapshot}, {"avi"}).resolve("repo", "rafa")
            self.assertEqual((route.slug, route.chain, route.source), ("avi", ("avi",), "projects"))
            self.assertEqual(json.loads(path.read_text())["version"], "routing/v2")

    def test_missing_health_fails_closed(self) -> None:
        with tempfile.TemporaryDirectory() as directory:
            path = Path(directory) / "routing_rules.json"
            path.write_text(json.dumps({"version": "routing/v2", "projects": {}, "default": "avi", "quota_exhausted_threshold_pct": 100}))
            with self.assertRaises(NoHealthyAccountError):
                RoutingResolver(load_rules(path), {}, {"avi"}).resolve(None)

    def test_dynamic_slug_is_reserved(self) -> None:
        with tempfile.TemporaryDirectory() as directory:
            registry = AccountRegistry(base_dir=Path(directory), legacy_codex_home=Path(directory) / "legacy")
            with self.assertRaises(ValueError):
                registry.new_slug("dynamic")


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