"""Scenario loading and validation utilities."""

import json
from pathlib import Path
from typing import Any

import yaml

from agenteval.models import Scenario


class ScenarioValidationError(Exception):
    """Raised when a scenario file fails validation."""

    pass


def load_scenario_file(path: Path) -> Scenario:
    """Load a scenario from a YAML or JSON file."""
    if not path.exists():
        raise ScenarioValidationError(f"scenario file not found: {path}")

    text = path.read_text(encoding="utf-8")
    suffix = path.suffix.lower()
    if suffix in {".yaml", ".yml"}:
        data = yaml.safe_load(text)
    elif suffix == ".json":
        data = json.loads(text)
    else:
        raise ScenarioValidationError(f"unsupported scenario file format: {suffix}")

    if not isinstance(data, dict):
        raise ScenarioValidationError("scenario file must contain a top-level object")

    return Scenario(**data)


def validate_scenario(data: dict[str, Any]) -> tuple[bool, list[str]]:
    """Validate raw scenario data without constructing the model."""
    errors: list[str] = []
    try:
        Scenario(**data)
    except Exception as exc:
        errors.append(str(exc))
        return False, errors
    return True, []


def scenario_to_yaml(scenario: Scenario) -> str:
    """Serialize a scenario to YAML."""
    return yaml.safe_dump(
        scenario.model_dump(exclude_none=True),
        allow_unicode=True,
        sort_keys=False,
    )


def scenario_to_json(scenario: Scenario, indent: int = 2) -> str:
    """Serialize a scenario to JSON."""
    return json.dumps(scenario.model_dump(exclude_none=True), ensure_ascii=False, indent=indent)
