"""Configuration for the embedding session orchestrator."""

from __future__ import annotations

from pathlib import Path
from typing import Optional

from pydantic import Field
from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
    """Application settings loaded from the environment."""

    docker_url: str = Field(
        default="unix:///var/run/docker.sock",
        description="Docker socket URL accessed by the orchestrator.",
    )
    container_image: str = Field(
        default="embedding-atlas:latest",
        description="Default Docker image used for embedding-atlas sessions.",
    )
    container_name_prefix: str = Field(
        default="embedding-atlas",
        description="Prefix applied to managed container names.",
    )
    container_host: str = Field(
        default="0.0.0.0",
        description="Host binding used inside managed containers.",
    )
    api_host: str = Field(
        default="0.0.0.0",
        description="Listening host for the FastAPI server.",
    )
    api_port: int = Field(
        default=9000,
        description="Listening port for the FastAPI server.",
    )
    default_port: int = Field(
        default=5055,
        description="Fallback embedding-atlas port when no override is provided.",
    )
    port_range_start: int = Field(
        default=6000,
        description="Lower bound for dynamically assigned ports.",
    )
    port_range_end: int = Field(
        default=6999,
        description="Upper bound for dynamically assigned ports (inclusive).",
    )
    session_root: Path = Field(
        default=Path("runtime/sessions"),
        description="Directory used to persist downloaded datasets per session.",
    )
    download_chunk_size: int = Field(
        default=64 * 1024,
        description="Chunk size in bytes when streaming remote datasets.",
    )
    download_timeout_seconds: int = Field(
        default=300,
        description="Timeout applied to dataset downloads.",
    )
    auto_remove_seconds: int = Field(
        default=36000,
        description="Default inactivity window before a session is garbage-collected (10h).",
    )
    cleanup_interval_seconds: int = Field(
        default=600,
        description="Background cleanup cadence in seconds.",
    )
    container_network: Optional[str] = Field(
        default=None,
        description="Optional Docker network to attach managed containers to.",
    )

    model_config = SettingsConfigDict(
        env_prefix="EMBEDDING_",
        env_file=".env",
        env_file_encoding="utf-8",
    )

    def prepare(self) -> None:
        """Ensure directories referenced by the settings exist."""

        self.session_root = self.session_root.resolve()
        self.session_root.mkdir(parents=True, exist_ok=True)


settings = Settings()
settings.prepare()
