"""Enrichment feature flags and guardrails."""

from __future__ import annotations

import os
from decimal import Decimal, InvalidOperation
from typing import Final, Optional


def _get_bool(name: str, default: bool = False) -> bool:
    value = os.getenv(name)
    if value is None:
        return default
    return value.strip().lower() in {"1", "true", "yes", "on"}


def _get_decimal(name: str, default: str, *, legacy: Optional[str] = None) -> Decimal:
    """
    Read a Decimal-valued environment variable with optional legacy fallback.
    """
    raw = os.getenv(name)
    if raw is None and legacy:
        raw = os.getenv(legacy)
    if raw is None:
        raw = default
    try:
        return Decimal(str(raw))
    except (InvalidOperation, TypeError, ValueError):
        return Decimal(default)


def _get_int(name: str, default: int, *, legacy: Optional[str] = None) -> int:
    """
    Read an integer-valued environment variable with optional legacy fallback.
    """
    raw = os.getenv(name)
    if raw is None and legacy:
        raw = os.getenv(legacy)
    if raw is None:
        return default
    try:
        return int(raw)
    except (TypeError, ValueError):
        return default


# Global enable/disable switch. Start life in the "off" position.
ENRICHMENT_ENABLED: Final[bool] = _get_bool("FM_ENRICHMENT_ENABLED", default=False)

# Absolute daily spend guardrail (in USD) across every account.
GLOBAL_SPEND_CAP_USD: Final[Decimal] = _get_decimal(
    "FM_ENRICHMENT_GLOBAL_CAP_USD",
    default="0",  # Require an explicit value before launch unless set in env.
    legacy="FM_ENRICHMENT_MAX_DAILY_SPEND_USD",
)

# Per-account daily spend guardrail (in USD) so a single customer cannot run wild.
PER_ACCOUNT_SPEND_CAP_USD: Final[Decimal] = _get_decimal(
    "FM_ENRICHMENT_PER_ACCOUNT_CAP_USD",
    default="0",
    legacy="FM_ENRICHMENT_MAX_DAILY_SPEND_PER_ACCOUNT_USD",
)

# TTL and heartbeat controls (seconds/hours).
RESERVATION_TTL_SECONDS: Final[int] = _get_int(
    "FM_ENRICHMENT_RESERVATION_TTL_SECONDS",
    default=600,
)
HEARTBEAT_SECONDS: Final[int] = _get_int(
    "FM_ENRICHMENT_HEARTBEAT_SECONDS",
    default=25,
)
HEARTBEAT_GRACE_SECONDS: Final[int] = _get_int(
    "FM_ENRICHMENT_HEARTBEAT_GRACE_SECONDS",
    default=120,
)
IDEMPOTENCY_TTL_HOURS: Final[int] = _get_int(
    "FM_ENRICHMENT_IDEMPOTENCY_TTL_HOURS",
    default=48,
)

# Backwards-compatible aliases while the rest of the code migrates.
MAX_GLOBAL_DAILY_SPEND_USD: Final[Decimal] = GLOBAL_SPEND_CAP_USD
MAX_ACCOUNT_DAILY_SPEND_USD: Final[Decimal] = PER_ACCOUNT_SPEND_CAP_USD


def enrichment_enabled() -> bool:
    """Return whether enrichment flows are allowed to proceed."""

    return ENRICHMENT_ENABLED
