"""Pydantic-free config parser — converts raw config dict to core types."""

from __future__ import annotations

from typing import Any

from pyfortis._types import (
    CircuitBreakerSpec,
    EscalationPolicy,
    LimitSpec,
    MetricSpec,
)
from pyfortis.errors import ConfigurationError


def raw_config_to_core(
    config: dict[str, Any],
) -> tuple[
    list[LimitSpec],
    list[MetricSpec],
    list[CircuitBreakerSpec],
    EscalationPolicy,
    dict[str, Any],
]:
    """Parse raw config dict into core types.

    Returns (limits, metrics, circuit_breakers, escalation_policy, meta).
    """
    meta = dict(config.get("meta", {}))

    # Limits
    limits: list[LimitSpec] = []
    for raw in config.get("limits", []):
        try:
            limits.append(LimitSpec.from_config(raw))
        except (KeyError, ValueError) as exc:
            raise ConfigurationError(
                f"Invalid limit config: {exc}",
                context={"raw": raw},
            ) from exc

    # Metrics
    metrics: list[MetricSpec] = []
    for raw in config.get("metrics", []):
        try:
            metrics.append(MetricSpec.from_config(raw))
        except (KeyError, ValueError) as exc:
            raise ConfigurationError(
                f"Invalid metric config: {exc}",
                context={"raw": raw},
            ) from exc

    # Circuit breakers
    circuit_breakers: list[CircuitBreakerSpec] = []
    for raw in config.get("circuit_breakers", []):
        try:
            circuit_breakers.append(CircuitBreakerSpec.from_config(raw))
        except (KeyError, ValueError) as exc:
            raise ConfigurationError(
                f"Invalid circuit breaker config: {exc}",
                context={"raw": raw},
            ) from exc

    # Breach/escalation policy
    breach_cfg = config.get("breach_policy", {})
    escalation_policy = EscalationPolicy.from_config(breach_cfg)

    return limits, metrics, circuit_breakers, escalation_policy, meta
