"""Configuration for {{ agent_name }}."""

from __future__ import annotations

import os
from dataclasses import dataclass


def _env_flag(name: str, default: bool) -> bool:
    """Parse boolean from environment variable."""
    raw = os.getenv(name)
    if raw is None:
        return default
    return raw.lower() in {"1", "true", "yes", "on"}


def _env_int(name: str, default: int) -> int:
    """Parse integer from environment variable."""
    raw = os.getenv(name)
    return int(raw) if raw is not None else default


def _env_float(name: str, default: float) -> float:
    """Parse float from environment variable."""
    raw = os.getenv(name)
    return float(raw) if raw is not None else default


def _env_str(name: str, default: str) -> str:
    """Parse string from environment variable."""
    raw = os.getenv(name)
    return raw if raw is not None else default


def _env_optional_str(name: str, default: str | None) -> str | None:
    """Parse optional string from environment variable."""
    raw = os.getenv(name)
    if raw is None:
        return default
    raw = raw.strip()
    return raw or None


@dataclass
class Config:
    """Environment-driven configuration.

    All settings can be overridden via environment variables.
    Use Config.from_env() to load from environment.
    """

    # LLM Configuration
    llm_model: str = "{{ primary_model }}"
    summarizer_model: str | None = None
    reflection_model: str | None = None

    # Feature Flags
    memory_enabled: bool = {{ memory_enabled }}
    summarizer_enabled: bool = {{ summarizer_enabled }}
    reflection_enabled: bool = {{ reflection_enabled }}
    short_term_memory_enabled: bool = {{ short_term_memory_enabled }}

    # Reflection Settings
    reflection_quality_threshold: float = {{ reflection_quality_threshold }}
    reflection_max_revisions: int = {{ reflection_max_revisions }}

    # Service URLs
    memory_base_url: str | None = {{ memory_base_url }}
    lighthouse_base_url: str | None = {{ lighthouse_base_url }}
    wayfinder_base_url: str | None = {{ wayfinder_base_url }}

    # Planner Settings
    planner_max_iters: int = {{ planner_max_iters }}
    planner_hop_budget: int = {{ planner_hop_budget }}
    planner_absolute_max_parallel: int = {{ planner_absolute_max_parallel }}
    planner_stream_final_response: bool = {{ planner_stream_final_response }}

    # Built-in Short-Term Memory (ReactPlanner)
    short_term_memory_strategy: str = {{ short_term_memory_strategy }}
    short_term_memory_full_zone_turns: int = {{ short_term_memory_full_zone_turns }}
    short_term_memory_summary_max_tokens: int = {{ short_term_memory_summary_max_tokens }}
    short_term_memory_total_max_tokens: int = {{ short_term_memory_total_max_tokens }}
    short_term_memory_overflow_policy: str = {{ short_term_memory_overflow_policy }}
    short_term_memory_tenant_key: str = {{ short_term_memory_tenant_key }}
    short_term_memory_user_key: str = {{ short_term_memory_user_key }}
    short_term_memory_session_key: str = {{ short_term_memory_session_key }}
    short_term_memory_require_explicit_key: bool = {{ short_term_memory_require_explicit_key }}
    short_term_memory_include_trajectory_digest: bool = {{ short_term_memory_include_trajectory_digest }}
    short_term_memory_summarizer_model: str | None = {{ short_term_memory_summarizer_model }}
    short_term_memory_recovery_backlog_limit: int = {{ short_term_memory_recovery_backlog_limit }}
    short_term_memory_retry_attempts: int = {{ short_term_memory_retry_attempts }}
    short_term_memory_retry_backoff_base_s: float = {{ short_term_memory_retry_backoff_base_s }}
    short_term_memory_degraded_retry_interval_s: float = {{ short_term_memory_degraded_retry_interval_s }}

    @classmethod
    def from_env(cls) -> Config:
        """Load configuration from environment variables."""
        return cls(
            # LLM Configuration
            llm_model=os.getenv("LLM_MODEL", "{{ primary_model }}"),
            summarizer_model=os.getenv("SUMMARIZER_MODEL"),
            reflection_model=os.getenv("REFLECTION_MODEL"),

            # Feature Flags
            memory_enabled=_env_flag("MEMORY_ENABLED", {{ memory_enabled }}),
            summarizer_enabled=_env_flag("SUMMARIZER_ENABLED", {{ summarizer_enabled }}),
            reflection_enabled=_env_flag("REFLECTION_ENABLED", {{ reflection_enabled }}),
            short_term_memory_enabled=_env_flag("SHORT_TERM_MEMORY_ENABLED", {{ short_term_memory_enabled }}),

            # Reflection Settings
            reflection_quality_threshold=_env_float("REFLECTION_QUALITY_THRESHOLD", {{ reflection_quality_threshold }}),
            reflection_max_revisions=_env_int("REFLECTION_MAX_REVISIONS", {{ reflection_max_revisions }}),

            # Service URLs (None if not set)
            memory_base_url=os.getenv("MEMORY_BASE_URL"),
            lighthouse_base_url=os.getenv("LIGHTHOUSE_BASE_URL"),
            wayfinder_base_url=os.getenv("WAYFINDER_BASE_URL"),

            # Planner Settings
            planner_max_iters=_env_int("PLANNER_MAX_ITERS", {{ planner_max_iters }}),
            planner_hop_budget=_env_int("PLANNER_HOP_BUDGET", {{ planner_hop_budget }}),
            planner_absolute_max_parallel=_env_int("PLANNER_ABSOLUTE_MAX_PARALLEL", {{ planner_absolute_max_parallel }}),
            planner_stream_final_response=_env_flag("PLANNER_STREAM_FINAL_RESPONSE", {{ planner_stream_final_response }}),

            # Built-in Short-Term Memory
            short_term_memory_strategy=_env_str("SHORT_TERM_MEMORY_STRATEGY", {{ short_term_memory_strategy }}),
            short_term_memory_full_zone_turns=_env_int(
                "SHORT_TERM_MEMORY_FULL_ZONE_TURNS",
                {{ short_term_memory_full_zone_turns }},
            ),
            short_term_memory_summary_max_tokens=_env_int(
                "SHORT_TERM_MEMORY_SUMMARY_MAX_TOKENS",
                {{ short_term_memory_summary_max_tokens }},
            ),
            short_term_memory_total_max_tokens=_env_int(
                "SHORT_TERM_MEMORY_TOTAL_MAX_TOKENS",
                {{ short_term_memory_total_max_tokens }},
            ),
            short_term_memory_overflow_policy=_env_str(
                "SHORT_TERM_MEMORY_OVERFLOW_POLICY",
                {{ short_term_memory_overflow_policy }},
            ),
            short_term_memory_tenant_key=_env_str(
                "SHORT_TERM_MEMORY_TENANT_KEY",
                {{ short_term_memory_tenant_key }},
            ),
            short_term_memory_user_key=_env_str(
                "SHORT_TERM_MEMORY_USER_KEY",
                {{ short_term_memory_user_key }},
            ),
            short_term_memory_session_key=_env_str(
                "SHORT_TERM_MEMORY_SESSION_KEY",
                {{ short_term_memory_session_key }},
            ),
            short_term_memory_require_explicit_key=_env_flag(
                "SHORT_TERM_MEMORY_REQUIRE_EXPLICIT_KEY",
                {{ short_term_memory_require_explicit_key }},
            ),
            short_term_memory_include_trajectory_digest=_env_flag(
                "SHORT_TERM_MEMORY_INCLUDE_TRAJECTORY_DIGEST",
                {{ short_term_memory_include_trajectory_digest }},
            ),
            short_term_memory_summarizer_model=_env_optional_str(
                "SHORT_TERM_MEMORY_SUMMARIZER_MODEL",
                {{ short_term_memory_summarizer_model }},
            ),
            short_term_memory_recovery_backlog_limit=_env_int(
                "SHORT_TERM_MEMORY_RECOVERY_BACKLOG_LIMIT",
                {{ short_term_memory_recovery_backlog_limit }},
            ),
            short_term_memory_retry_attempts=_env_int(
                "SHORT_TERM_MEMORY_RETRY_ATTEMPTS",
                {{ short_term_memory_retry_attempts }},
            ),
            short_term_memory_retry_backoff_base_s=_env_float(
                "SHORT_TERM_MEMORY_RETRY_BACKOFF_BASE_S",
                {{ short_term_memory_retry_backoff_base_s }},
            ),
            short_term_memory_degraded_retry_interval_s=_env_float(
                "SHORT_TERM_MEMORY_DEGRADED_RETRY_INTERVAL_S",
                {{ short_term_memory_degraded_retry_interval_s }},
            ),
        )
