from __future__ import annotations

import json
import sys
from pathlib import Path

import pytest

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from routing_resolver import RoutingRules, load_rules

KNOWN_SLUGS = {"avi", "rafa", "roy", "zync2"}


def _write_rules(path: Path, payload: dict[str, object]) -> None:
    path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")


def test_load_rules_accepts_valid_account_caps(tmp_path: Path) -> None:
    path = tmp_path / "routing_rules.json"
    _write_rules(
        path,
        {
            "version": "routing/v2",
            "projects": {},
            "default": "rafa",
            "fallback_chain": [],
            "quota_exhausted_threshold_pct": 100,
            "account_caps": {
                "zync2": {"7d": 10},
                "multideal": {"5h": 25, "7d": 40},
            },
        },
    )

    rules = load_rules(path, known_slugs=KNOWN_SLUGS | {"zync2", "multideal"})

    assert rules.account_caps == {
        "zync2": {"7d": 10},
        "multideal": {"5h": 25, "7d": 40},
    }


@pytest.mark.parametrize(
    ("account_caps", "message"),
    [
        ({"zync2": {"1w": 10}}, "window keys"),
        ({"zync2": {"7d": 0}}, "1 to 100"),
        ({"zync2": {"7d": 101}}, "1 to 100"),
        ({"zync2": {"7d": "10"}}, "1 to 100"),
        ({"unknown": {"7d": 10}}, "not in the registry"),
        ("bad", "must be an object"),
    ],
)
def test_load_rules_rejects_invalid_account_caps(
    tmp_path: Path,
    account_caps: object,
    message: str,
) -> None:
    path = tmp_path / "routing_rules.json"
    _write_rules(
        path,
        {
            "version": "routing/v2",
            "projects": {},
            "default": "rafa",
            "fallback_chain": [],
            "quota_exhausted_threshold_pct": 100,
            "account_caps": account_caps,
        },
    )

    with pytest.raises(ValueError, match=message):
        load_rules(path, known_slugs=KNOWN_SLUGS | {"zync2"})


def test_load_rules_account_caps_round_trip_through_v2_migration_rewrite(tmp_path: Path) -> None:
    path = tmp_path / "routing_rules.json"
    _write_rules(
        path,
        {
            "projects": {"repo": "rafa"},
            "default": "rafa",
            "fallback_chain": ["roy"],
            "quota_exhausted_threshold_pct": 100,
            "account_caps": {"zync2": {"7d": 10}},
        },
    )

    rules = load_rules(path, known_slugs=KNOWN_SLUGS | {"zync2"})

    assert rules.account_caps == {"zync2": {"7d": 10}}
    migrated = json.loads(path.read_text(encoding="utf-8"))
    assert migrated["version"] == "routing/v2"
    assert migrated["account_caps"] == {"zync2": {"7d": 10}}

    reloaded = load_rules(path, known_slugs=KNOWN_SLUGS | {"zync2"})
    assert isinstance(reloaded, RoutingRules)
    assert reloaded.account_caps == {"zync2": {"7d": 10}}
