"""Configuration via crondag.toml + env vars."""
from __future__ import annotations

import tomllib
from pathlib import Path
from pydantic_settings import BaseSettings
from pydantic import Field


def _load_toml() -> dict:
    """Load crondag.toml from CWD if it exists."""
    path = Path.cwd() / "crondag.toml"
    if path.exists():
        with open(path, "rb") as f:
            data = tomllib.load(f)
        # Flatten: [crondag] section + [scheduler] + [webserver]
        flat = {}
        flat.update(data.get("crondag", {}))
        flat.update({f"scheduler_{k}": v for k, v in data.get("scheduler", {}).items()})
        flat.update({f"webserver_{k}": v for k, v in data.get("webserver", {}).items()})
        return flat
    return {}


class Settings(BaseSettings):
    model_config = {"env_prefix": "CRONDAG_", "extra": "ignore"}

    # Core
    dags_dir: str = Field(default="./dags", description="Directory containing DAG files")
    database_url: str = Field(default="sqlite+aiosqlite:///./crondag.db", description="Database URL")
    log_level: str = Field(default="INFO", description="Log level")
    data_dir: str = Field(default="./data", description="Data directory")

    # Scheduler
    scheduler_dag_scan_interval: int = Field(default=30, description="Seconds between DAG folder scans")
    scheduler_max_active_tasks: int = Field(default=4, description="Max concurrent task executions")
    scheduler_timezone: str = Field(default="UTC", description="Default timezone")
    scheduler_loop_interval: float = Field(default=1.0, description="Scheduler loop sleep interval")
    scheduler_max_active_runs_per_dag: int = Field(default=1, description="Max active runs per DAG")

    # Webserver
    webserver_host: str = Field(default="0.0.0.0", description="Web server host")
    webserver_port: int = Field(default=8080, description="Web server port")
    webserver_enabled: bool = Field(default=True, description="Enable web server")


def get_settings() -> Settings:
    """Create settings, merging TOML file with env vars."""
    toml_values = _load_toml()
    return Settings(**toml_values)
