# ============================================================
# Configuration — environment variables with defaults
# ============================================================
import os
from pathlib import Path

from dotenv import load_dotenv

load_dotenv(Path(__file__).resolve().parents[2] / ".env")


# -------------------- Database — handled in database.py --------------------

# -------------------- CORS --------------------
def get_cors_origins() -> list[str]:
    origins = os.getenv("CORS_ORIGINS", "http://localhost:3000")
    return [o.strip() for o in origins.split(",") if o.strip()]


def get_config_value(key_name: str, default: str = "") -> str:
    """Read runtime config from system_config, falling back to environment."""
    try:
        from app.core.database import SessionLocal
        from app.core.models import SystemConfig

        db = SessionLocal()
        try:
            row = db.get(SystemConfig, key_name)
            if row and row.key_value is not None:
                return row.key_value
        finally:
            db.close()
    except Exception:
        pass

    env_key = key_name.upper()
    return os.getenv(env_key, default)


# -------------------- SMTP --------------------
def get_smtp_config() -> dict:
    return {
        "host": get_config_value("smtp_host"),
        "port": int(get_config_value("smtp_port", "587")),
        "user": get_config_value("smtp_user"),
        "password": get_config_value("smtp_password"),
        "from_name": get_config_value("smtp_from_name", "ERP System"),
        "from_email": get_config_value("smtp_from_email"),
        "use_tls": get_config_value("smtp_use_tls", "true").lower() in ("true", "1", "yes"),
    }


# -------------------- Telegram --------------------
def get_telegram_config() -> dict:
    return {
        "bot_token": get_config_value("telegram_bot_token"),
        "chat_id": get_config_value("telegram_chat_id"),
    }


# -------------------- AI --------------------
def get_ai_config() -> dict:
    return {
        "model": get_config_value("ai_model", "minimax/minimax-m2.7"),
        "api_key": get_config_value("ai_api_key"),
    }
