"""Tests for legacy latency validation behavior."""

import os
import tempfile
import yaml

from cli.config_migration import migrate_config_data
from cli.parser import parse_user_config
from cli.validator import validate_user_config


def _parse_config(config_yaml: str):
    data = yaml.safe_load(config_yaml)
    providers = data.get("providers") if isinstance(data, dict) else None
    models = providers.get("models", []) if isinstance(providers, dict) else []
    if isinstance(data, dict) and (
        "signals" in data
        or "decisions" in data
        or any(isinstance(model, dict) and "endpoints" in model for model in models)
    ):
        data = migrate_config_data(data)

    with tempfile.NamedTemporaryFile(mode="w", suffix=".yaml", delete=False) as f:
        yaml.safe_dump(data, f, sort_keys=False)
        temp_path = f.name

    try:
        return parse_user_config(temp_path)
    finally:
        os.unlink(temp_path)


def test_validate_rejects_legacy_latency_condition():
    config_yaml = """
version: v0.1
listeners:
  - name: "http-8888"
    address: "0.0.0.0"
    port: 8888
signals:
  domains:
    - name: "math"
      description: "Math domain"
decisions:
  - name: "math_decision"
    description: "Math decision"
    priority: 100
    rules:
      operator: "AND"
      conditions:
        - type: "domain"
          name: "math"
        - type: "latency"
          name: "low_latency"
    modelRefs:
      - model: "test_model"
    algorithm:
      type: "latency_aware"
      latency_aware:
        tpot_percentile: 20
providers:
  models:
    - name: "test_model"
      endpoints:
        - name: "ep1"
          weight: 1
          endpoint: "localhost:8000"
  default_model: "test_model"
"""

    config = _parse_config(config_yaml)
    errors = validate_user_config(config)

    assert any(
        "legacy latency config is no longer supported" in str(error) for error in errors
    )


def test_validate_accepts_latency_aware_configuration():
    config_yaml = """
version: v0.1
listeners:
  - name: "http-8888"
    address: "0.0.0.0"
    port: 8888
signals:
  domains:
    - name: "math"
      description: "Math domain"
decisions:
  - name: "math_decision"
    description: "Math decision"
    priority: 100
    rules:
      operator: "AND"
      conditions:
        - type: "domain"
          name: "math"
    modelRefs:
      - model: "test_model"
    algorithm:
      type: "latency_aware"
      latency_aware:
        tpot_percentile: 20
        ttft_percentile: 20
providers:
  models:
    - name: "test_model"
      endpoints:
        - name: "ep1"
          weight: 1
          endpoint: "localhost:8000"
  default_model: "test_model"
"""

    config = _parse_config(config_yaml)
    errors = validate_user_config(config)

    assert errors == []
