"""
Application configuration from environment.
Single source of truth for DB connection and app settings.
"""
import os
import tempfile
from pathlib import Path
from typing import Dict, Any

try:
    from dotenv import load_dotenv
    _has_dotenv = True
except ImportError:
    _has_dotenv = False

_root = Path(__file__).resolve().parents[2]  # project root


def _read_env_file_into_os(path: Path) -> None:
    """Parse .env and set os.environ for KEY=value lines. Fallback when load_dotenv doesn't run in worker."""
    try:
        with open(path, "r", encoding="utf-8") as f:
            for line in f:
                line = line.strip()
                if not line or line.startswith("#") or "=" not in line:
                    continue
                key, _, value = line.partition("=")
                key = key.strip()
                value = value.strip().strip('"').strip("'")
                if key:
                    os.environ[key] = value
    except Exception:
        pass


def _ensure_env_loaded():
    """Load .env from project root so DB_PASSWORD etc. are set (e.g. under uvicorn --reload)."""
    for p in [_root / ".env", Path.cwd() / ".env"]:
        if not p.exists():
            continue
        if _has_dotenv:
            load_dotenv(p, override=True)
        _read_env_file_into_os(p)  # fallback: set os.environ from file if load_dotenv didn't
        break


# Load .env as soon as config is imported (so worker process has DB_PASSWORD)
_ensure_env_loaded()


def get_env(key: str, default: str = "") -> str:
    return os.environ.get(key, default).strip()


# -----------------------------------------------------------------------------
# Database connection (MySQL or MSSQL)
# -----------------------------------------------------------------------------
def get_db_config() -> Dict[str, Any]:
    """
    Build database config from environment. Used by auth, browser service, boundary.
    Env: DB_TYPE (mysql|mssql), DB_HOST, DB_PORT, DB_NAME, DB_USER, DB_PASSWORD,
         DB_SERVER (MSSQL), DB_DRIVER (MSSQL), DB_CHARSET (MySQL).
    """
    db_type = get_env("DB_TYPE", "mysql").lower()
    if db_type == "mysql":
        password = get_env("DB_PASSWORD", "")
        if not password:
            _ensure_env_loaded()
            password = get_env("DB_PASSWORD", "")
        return {
            "type": "mysql",
            "host": get_env("DB_HOST", "localhost"),
            "port": int(get_env("DB_PORT", "3306")),
            "database": get_env("DB_NAME", "LRS43"),
            "username": get_env("DB_USER", "root"),
            "password": password,
            "charset": get_env("DB_CHARSET", "utf8mb4"),
        }
    # MSSQL
    return {
        "type": "mssql",
        "server": get_env("DB_SERVER", "MSSQL_LRS43"),
        "port": int(get_env("DB_PORT", "1433")),
        "database": get_env("DB_NAME", "LRS43"),
        "username": get_env("DB_USER", "root"),
        "password": get_env("DB_PASSWORD", ""),
        "driver": get_env("DB_DRIVER", "FreeTDS"),
        "encrypt": "no",
        "trust_server_certificate": "yes",
    }


# Auth (industry standard: short-lived access, refresh token)
ACCESS_TOKEN_EXPIRE_MINUTES = int(get_env("ACCESS_TOKEN_EXPIRE_MINUTES", "15"))
REFRESH_TOKEN_EXPIRE_DAYS = int(get_env("REFRESH_TOKEN_EXPIRE_DAYS", "7"))
AUTH_SECRET_KEY = get_env("AUTH_SECRET_KEY") or "dev-secret-key-change-in-production-min-32-chars"
REFRESH_SECRET_KEY = get_env("REFRESH_SECRET_KEY") or get_env("AUTH_SECRET_KEY") or AUTH_SECRET_KEY

# Rate limiting (login)
LOGIN_RATE_LIMIT_PER_MINUTE = int(get_env("LOGIN_RATE_LIMIT_PER_MINUTE", "10"))

# Paths
TEMP_PDF_DIR = get_env("TEMP_PDF_DIR") or os.path.join(tempfile.gettempdir(), "aumentum_pdfs")
CONTENTSTORE_BASE = get_env("CONTENTSTORE_BASE", os.path.expanduser("~/aumentum_contentstore"))
