"""Unit tests for Pi Model Router catalog compilation and multi-account expansion."""

import os
import sys
from pathlib import Path
import pytest
import yaml

ROOT_DIR = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT_DIR / "scripts"))

from render_config import load_catalog, render, validate_catalog


@pytest.fixture
def catalog_dir() -> Path:
    return ROOT_DIR / "templates" / "catalog"


def test_modular_catalog_loads_and_merges_sections(catalog_dir: Path) -> None:
    """Verify load_catalog merges settings.yml, routing.yml, and providers.yml into a valid catalog."""
    catalog = load_catalog(catalog_dir)
    assert catalog.get("version") == 1
    assert "settings" in catalog
    assert "routing" in catalog
    assert "providers" in catalog
    assert "tiers" in catalog["routing"]
    assert "pools" in catalog["routing"]
    assert "modelRoles" in catalog["routing"]
    assert "fallbackChains" in catalog["routing"]


def test_catalog_rendering_expands_tiers_and_pools(catalog_dir: Path) -> None:
    """Verify render() expands @tier, @pool, and @account references into flat valid selectors."""
    catalog = load_catalog(catalog_dir)
    config, models = render(catalog)
    validate_catalog(catalog, config, models)

    # 1. Check generated config.yml structure
    assert "modelRoles" in config
    assert "retry" in config
    assert "fallbackChains" in config["retry"]
    assert "@tier." not in str(config)
    assert "@pool." not in str(config)
    assert "@account." not in str(config)

    # 2. Check Luna escalation in default chain
    default_chain = config["retry"]["fallbackChains"]["default"]
    assert any("gpt-5.6-luna" in item for item in default_chain), (
        "default fallback chain must include gpt-5.6-luna for auto-escalation"
    )

    # 3. Check Ox-Alpha free pool prioritization
    assert any("ox-alpha" in item for item in default_chain), (
        "default fallback chain must include stealth/ox-alpha"
    )


def test_multi_account_providers_and_headers_preservation(catalog_dir: Path) -> None:
    """Verify multi-account providers expand into separate entries and retain WAF headers."""
    catalog = load_catalog(catalog_dir)
    _, models = render(catalog)
    providers = models.get("providers", {})

    # Custom gateway multi-account check
    for gw_id in ["custom-gateway-1", "custom-gateway-2"]:
        assert gw_id in providers, f"{gw_id} must be expanded in models.yml"
        p_cfg = providers[gw_id]
        assert p_cfg.get("api") == "openai-completions"
        assert p_cfg.get("headers", {}).get("User-Agent") == "opencode/1.1.20"
        assert p_cfg.get("headers", {}).get("x-client-name") == "opencode"



def test_probe_script_resolves_package_paths() -> None:
    """probe_free_models.py must locate templates/catalog and tests/ relative to the package root,
    not the scripts/ directory it lives in (regression: --audit failed with 'no tests ran')."""
    import probe_free_models as probe

    assert probe.CATALOG_DIR.is_dir(), f"catalog dir not found at {probe.CATALOG_DIR}"
    assert (probe.CATALOG_DIR / "routing.yml").is_file()
    assert probe.TEST_CONFIG_PATH.is_file(), f"test module not found at {probe.TEST_CONFIG_PATH}"
    assert probe.CATALOG_PATH == probe.CATALOG_DIR
