"""Application settings."""

from __future__ import annotations

import os
from dataclasses import dataclass
from pathlib import Path

DEFAULT_APP_NAME = "ORION-AI"


def _load_dotenv_file() -> None:
    """Load local .env file without overriding real environment variables."""
    root = Path(__file__).resolve().parents[2]
    dotenv_path = root / ".env"
    if not dotenv_path.exists():
        return

    for raw_line in dotenv_path.read_text(encoding="utf-8").splitlines():
        line = raw_line.strip()
        if not line or line.startswith("#"):
            continue

        if line.startswith("export "):
            line = line[len("export ") :].strip()

        if "=" not in line:
            continue

        key, value = line.split("=", maxsplit=1)
        key = key.strip()
        value = value.strip()
        if not key:
            continue

        if len(value) >= 2 and value[0] == value[-1] and value[0] in {'"', "'"}:
            value = value[1:-1]
        os.environ.setdefault(key, value)


def _default_db_path() -> Path:
    """Build the default SQLite file path."""
    return Path(__file__).resolve().parents[2] / "database" / "sentineledge.db"


def _resolve_db_path(raw_path: str | None) -> Path:
    """Resolve an optional DB path from environment variables."""
    if not raw_path:
        return _default_db_path()

    path = Path(raw_path).expanduser()
    if path.is_absolute():
        return path

    return (Path(__file__).resolve().parents[2] / path).resolve()


def _parse_mode(raw_mode: str | None) -> str:
    """Normalize runtime mode value."""
    value = (raw_mode or "dev").strip().lower()
    if value in {"prod", "production"}:
        return "production"
    return "dev"


def _split_csv(raw_value: str | None) -> list[str]:
    """Split comma-separated string into non-empty items."""
    if not raw_value:
        return []
    return [item.strip() for item in raw_value.split(",") if item.strip()]


def _default_cors_origins() -> list[str]:
    """Return default explicit CORS origins for local development."""
    return [
        "http://localhost",
        "https://localhost",
        "http://127.0.0.1",
        "https://127.0.0.1",
    ]


def _normalize_log_level(raw_level: str | None, fallback: str) -> str:
    """Normalize configured log level into one of Python standard names."""
    value = str(raw_level or "").strip().upper()
    if value in {"CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG"}:
        return value
    return fallback


def _default_log_level(mode: str) -> str:
    """Return secure default log level by runtime mode."""
    return "WARNING" if mode == "production" else "INFO"


def _parse_bool(raw_value: str | None, default: bool) -> bool:
    """Parse boolean-like env values with fallback."""
    if raw_value is None:
        return default
    return raw_value.strip().lower() in {"1", "true", "yes", "on"}


@dataclass(frozen=True)
class Settings:
    """Runtime application settings."""

    app_name: str
    db_path: Path
    app_mode: str
    sentineledge_api_key: str | None
    cors_allowed_origins: list[str]
    todoist_api_token: str | None
    ai_provider: str
    gemini_api_key: str | None
    gemini_model: str
    openai_api_key: str | None
    openai_model: str
    ollama_base_url: str
    ollama_model: str
    ai_allow_fallback: bool
    ai_reports_enabled: bool
    log_level: str
    privacy_mode: bool

    @property
    def database_url(self) -> str:
        """Return a SQLAlchemy-compatible SQLite URL."""
        return f"sqlite:///{self.db_path}"

    @property
    def is_production(self) -> bool:
        """Return True when running in production mode."""
        return self.app_mode == "production"


_load_dotenv_file()

_app_mode = _parse_mode(os.getenv("APP_ENV") or os.getenv("ENV"))
_extra_origins = _split_csv(os.getenv("CORS_ALLOWED_ORIGINS"))
_cors_origins = [] if _app_mode == "production" else [*_default_cors_origins()]
for origin in _extra_origins:
    if origin not in _cors_origins:
        _cors_origins.append(origin)


settings = Settings(
    app_name=os.getenv("APP_NAME", DEFAULT_APP_NAME),
    db_path=_resolve_db_path(os.getenv("DB_PATH")),
    app_mode=_app_mode,
    sentineledge_api_key=os.getenv("SENTINELEDGE_API_KEY"),
    cors_allowed_origins=_cors_origins,
    todoist_api_token=os.getenv("TODOIST_API_TOKEN"),
    ai_provider=os.getenv("AI_PROVIDER", "gemini").strip().lower(),
    gemini_api_key=os.getenv("GEMINI_API_KEY"),
    gemini_model=os.getenv("GEMINI_MODEL", "gemini-2.5-flash"),
    openai_api_key=os.getenv("OPENAI_API_KEY"),
    openai_model=os.getenv("OPENAI_MODEL", "gpt-4o-mini"),
    ollama_base_url=os.getenv("OLLAMA_BASE_URL", "http://localhost:11434").rstrip("/"),
    ollama_model=os.getenv("OLLAMA_MODEL", "llama3.2:3b"),
    ai_allow_fallback=os.getenv("AI_ALLOW_FALLBACK", "false").strip().lower() in {"1", "true", "yes", "on"},
    ai_reports_enabled=os.getenv("AI_REPORTS_ENABLED", "true").strip().lower() in {"1", "true", "yes", "on"},
    log_level=_normalize_log_level(os.getenv("LOG_LEVEL"), _default_log_level(_app_mode)),
    privacy_mode=_parse_bool(os.getenv("PRIVACY_MODE"), default=_app_mode == "production"),
)
