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

from __future__ import annotations

import os
from dataclasses import dataclass, field


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_csv(name: str, default: list[str]) -> list[str]:
    """Parse comma-separated list from environment variable."""
    raw = os.getenv(name)
    if raw is None:
        return default
    items = [item.strip() for item in raw.split(",") if item.strip()]
    return items


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 }}
{% if with_background_tasks %}
    background_tasks_enabled: bool = {{ background_tasks_enabled }}
{% endif %}

    # 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 }}
    rag_server_base_url: str | None = {{ rag_server_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 }}
    planner_multi_action_sequential: bool = {{ planner_multi_action_sequential }}
    planner_multi_action_read_only_only: bool = {{ planner_multi_action_read_only_only }}
    planner_multi_action_max_tools: int = {{ planner_multi_action_max_tools }}

    # Artifact Store (binary/large text)
    artifact_store_enabled: bool = {{ artifact_store_enabled }}
    artifact_store_ttl_seconds: int = {{ artifact_store_ttl_seconds }}
    artifact_store_max_artifact_bytes: int = {{ artifact_store_max_artifact_bytes }}
    artifact_store_max_session_bytes: int = {{ artifact_store_max_session_bytes }}
    artifact_store_max_trace_bytes: int = {{ artifact_store_max_trace_bytes }}
    artifact_store_max_artifacts_per_trace: int = {{ artifact_store_max_artifacts_per_trace }}
    artifact_store_max_artifacts_per_session: int = {{ artifact_store_max_artifacts_per_session }}
    artifact_store_cleanup_strategy: str = "{{ artifact_store_cleanup_strategy }}"

    # Rich Output (Component Artifacts)
    rich_output_enabled: bool = {{ rich_output_enabled }}
    rich_output_allowlist: list[str] = field(default_factory=lambda: {{ rich_output_allowlist }})
    rich_output_include_prompt_catalog: bool = {{ rich_output_include_prompt_catalog }}
    rich_output_include_prompt_examples: bool = {{ rich_output_include_prompt_examples }}
    rich_output_max_payload_bytes: int = {{ rich_output_max_payload_bytes }}
    rich_output_max_total_bytes: int = {{ rich_output_max_total_bytes }}

    # 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 }}

{% if with_background_tasks %}
    # Background Tasks (ReactPlanner + SessionManager)
    background_tasks_allow_tool_background: bool = {{ background_tasks_allow_tool_background }}
    background_tasks_default_mode: str = "{{ background_tasks_default_mode }}"
    background_tasks_default_merge_strategy: str = "{{ background_tasks_default_merge_strategy }}"
    background_tasks_context_depth: str = "{{ background_tasks_context_depth }}"
    background_tasks_propagate_on_cancel: str = "{{ background_tasks_propagate_on_cancel }}"
    background_tasks_spawn_requires_confirmation: bool = {{ background_tasks_spawn_requires_confirmation }}
    background_tasks_include_prompt_guidance: bool = {{ background_tasks_include_prompt_guidance }}
    background_tasks_max_concurrent_tasks: int = {{ background_tasks_max_concurrent_tasks }}
    background_tasks_max_tasks_per_session: int = {{ background_tasks_max_tasks_per_session }}
    background_tasks_task_timeout_s: int = {{ background_tasks_task_timeout_s }}
    background_tasks_max_pending_steering: int = {{ background_tasks_max_pending_steering }}
{% endif %}

    @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 }}),
{% if with_background_tasks %}
            background_tasks_enabled=_env_flag("BACKGROUND_TASKS_ENABLED", {{ background_tasks_enabled }}),
{% endif %}

            # 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"),
            rag_server_base_url=os.getenv("RAG_SERVER_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 }}),
            planner_multi_action_sequential=_env_flag(
                "PLANNER_MULTI_ACTION_SEQUENTIAL",
                {{ planner_multi_action_sequential }},
            ),
            planner_multi_action_read_only_only=_env_flag(
                "PLANNER_MULTI_ACTION_READ_ONLY_ONLY",
                {{ planner_multi_action_read_only_only }},
            ),
            planner_multi_action_max_tools=_env_int(
                "PLANNER_MULTI_ACTION_MAX_TOOLS",
                {{ planner_multi_action_max_tools }},
            ),

            # Artifact Store (binary/large text)
            artifact_store_enabled=_env_flag("ARTIFACT_STORE_ENABLED", {{ artifact_store_enabled }}),
            artifact_store_ttl_seconds=_env_int("ARTIFACT_STORE_TTL_SECONDS", {{ artifact_store_ttl_seconds }}),
            artifact_store_max_artifact_bytes=_env_int(
                "ARTIFACT_STORE_MAX_ARTIFACT_BYTES",
                {{ artifact_store_max_artifact_bytes }},
            ),
            artifact_store_max_session_bytes=_env_int(
                "ARTIFACT_STORE_MAX_SESSION_BYTES",
                {{ artifact_store_max_session_bytes }},
            ),
            artifact_store_max_trace_bytes=_env_int(
                "ARTIFACT_STORE_MAX_TRACE_BYTES",
                {{ artifact_store_max_trace_bytes }},
            ),
            artifact_store_max_artifacts_per_trace=_env_int(
                "ARTIFACT_STORE_MAX_ARTIFACTS_PER_TRACE",
                {{ artifact_store_max_artifacts_per_trace }},
            ),
            artifact_store_max_artifacts_per_session=_env_int(
                "ARTIFACT_STORE_MAX_ARTIFACTS_PER_SESSION",
                {{ artifact_store_max_artifacts_per_session }},
            ),
            artifact_store_cleanup_strategy=_env_str(
                "ARTIFACT_STORE_CLEANUP_STRATEGY",
                "{{ artifact_store_cleanup_strategy }}",
            ),

            # Rich Output (Component Artifacts)
            rich_output_enabled=_env_flag("RICH_OUTPUT_ENABLED", {{ rich_output_enabled }}),
            rich_output_allowlist=_env_csv(
                "RICH_OUTPUT_ALLOWLIST",
                {{ rich_output_allowlist }},
            ),
            rich_output_include_prompt_catalog=_env_flag(
                "RICH_OUTPUT_INCLUDE_PROMPT_CATALOG",
                {{ rich_output_include_prompt_catalog }},
            ),
            rich_output_include_prompt_examples=_env_flag(
                "RICH_OUTPUT_INCLUDE_PROMPT_EXAMPLES",
                {{ rich_output_include_prompt_examples }},
            ),
            rich_output_max_payload_bytes=_env_int(
                "RICH_OUTPUT_MAX_PAYLOAD_BYTES",
                {{ rich_output_max_payload_bytes }},
            ),
            rich_output_max_total_bytes=_env_int(
                "RICH_OUTPUT_MAX_TOTAL_BYTES",
                {{ rich_output_max_total_bytes }},
            ),

            # 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 }},
            ),
{% if with_background_tasks %}

            # Background Tasks
            background_tasks_allow_tool_background=_env_flag(
                "BACKGROUND_TASKS_ALLOW_TOOL_BACKGROUND",
                {{ background_tasks_allow_tool_background }},
            ),
            background_tasks_default_mode=_env_str(
                "BACKGROUND_TASKS_DEFAULT_MODE",
                "{{ background_tasks_default_mode }}",
            ),
            background_tasks_default_merge_strategy=_env_str(
                "BACKGROUND_TASKS_DEFAULT_MERGE_STRATEGY",
                "{{ background_tasks_default_merge_strategy }}",
            ),
            background_tasks_context_depth=_env_str(
                "BACKGROUND_TASKS_CONTEXT_DEPTH",
                "{{ background_tasks_context_depth }}",
            ),
            background_tasks_propagate_on_cancel=_env_str(
                "BACKGROUND_TASKS_PROPAGATE_ON_CANCEL",
                "{{ background_tasks_propagate_on_cancel }}",
            ),
            background_tasks_spawn_requires_confirmation=_env_flag(
                "BACKGROUND_TASKS_SPAWN_REQUIRES_CONFIRMATION",
                {{ background_tasks_spawn_requires_confirmation }},
            ),
            background_tasks_include_prompt_guidance=_env_flag(
                "BACKGROUND_TASKS_INCLUDE_PROMPT_GUIDANCE",
                {{ background_tasks_include_prompt_guidance }},
            ),
            background_tasks_max_concurrent_tasks=_env_int(
                "BACKGROUND_TASKS_MAX_CONCURRENT_TASKS",
                {{ background_tasks_max_concurrent_tasks }},
            ),
            background_tasks_max_tasks_per_session=_env_int(
                "BACKGROUND_TASKS_MAX_TASKS_PER_SESSION",
                {{ background_tasks_max_tasks_per_session }},
            ),
            background_tasks_task_timeout_s=_env_int(
                "BACKGROUND_TASKS_TASK_TIMEOUT_S",
                {{ background_tasks_task_timeout_s }},
            ),
            background_tasks_max_pending_steering=_env_int(
                "BACKGROUND_TASKS_MAX_PENDING_STEERING",
                {{ background_tasks_max_pending_steering }},
            ),
{% endif %}
        )
