from __future__ import annotations

import os
from dataclasses import dataclass
from pathlib import Path


BASE_DIR = Path(__file__).resolve().parents[1]


def load_env(path: Path | None = None) -> None:
    env_path = path or BASE_DIR / ".env"
    if not env_path.exists():
        return

    for raw_line in env_path.read_text(encoding="utf-8").splitlines():
        line = raw_line.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        key, value = line.split("=", 1)
        key = key.strip()
        value = value.strip().strip('"').strip("'")
        os.environ.setdefault(key, value)


@dataclass(frozen=True)
class Settings:
    telegram_token: str
    api_url: str
    api_token: str
    anthropic_api_key: str
    groq_api_key: str
    gmail_user: str
    gmail_password: str
    data_dir: Path
    timezone: str = "Asia/Baku"


def get_settings() -> Settings:
    load_env()
    data_dir = Path(os.environ.get("DATA_DIR", BASE_DIR / "data"))
    data_dir.mkdir(parents=True, exist_ok=True)

    return Settings(
        telegram_token=os.environ.get("TELEGRAM_TOKEN", ""),
        api_url=os.environ.get("API_URL", "http://127.0.0.1/api.php"),
        api_token=os.environ.get("API_TOKEN", ""),
        anthropic_api_key=os.environ.get("ANTHROPIC_API_KEY", ""),
        groq_api_key=os.environ.get("GROQ_API_KEY", ""),
        gmail_user=os.environ.get("GMAIL_USER", ""),
        gmail_password=os.environ.get("GMAIL_PASSWORD", ""),
        data_dir=data_dir,
        timezone=os.environ.get("TZ", "Asia/Baku"),
    )

