# ============================================================
# Configuration — environment variables with defaults
# ============================================================
import os
from pathlib import Path

from dotenv import load_dotenv
from app.core.security import PLATFORM_TENANT_CODE

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 environment only.

    Tenant-scoped DB config uses get_tenant_config_value instead.
    """
    # ponytail: DB query removed — SystemConfig PK is now (id) with tenant scope,
    # so a key-only lookup is invalid. Infrastructure callers fall back to env vars.
    env_key = key_name.upper()
    return os.getenv(env_key, default)


def get_tenant_config_value(db, tenant_id: int, key_name: str, default: str = "") -> str:
    """Read a tenant-scoped config value from system_config."""
    from sqlalchemy import select
    from app.core.models import SystemConfig

    row = db.execute(
        select(SystemConfig).where(
            SystemConfig.tenant_id == tenant_id,
            SystemConfig.key_name == key_name,
        )
    ).scalar_one_or_none()
    return row.key_value if row and row.key_value is not None else default


# -------------------- SMTP --------------------
def _tenant_value(db, tenant_id: int | None, key_name: str, default: str = "") -> str:
    if db is not None and tenant_id is not None:
        return get_tenant_config_value(db, tenant_id, key_name, get_config_value(key_name, default))
    return get_config_value(key_name, default)


def get_smtp_config(db=None, tenant_id: int | None = None) -> dict:
    return {
        "host": _tenant_value(db, tenant_id, "smtp_host"),
        "port": int(_tenant_value(db, tenant_id, "smtp_port", "587")),
        "user": _tenant_value(db, tenant_id, "smtp_user"),
        "password": _tenant_value(db, tenant_id, "smtp_password"),
        "from_name": _tenant_value(db, tenant_id, "smtp_from_name", "ERP System"),
        "from_email": _tenant_value(db, tenant_id, "smtp_from_email"),
        "use_tls": _tenant_value(db, tenant_id, "smtp_use_tls", "true").lower() in ("true", "1", "yes"),
    }


# -------------------- Telegram --------------------
def get_telegram_config(db=None, tenant_id: int | None = None) -> dict:
    if db is not None and tenant_id is not None:
        from sqlalchemy import select
        from app.core.models import Tenant

        tenant = db.get(Tenant, tenant_id)
        if tenant and tenant.company_code != PLATFORM_TENANT_CODE and tenant.telegram_use_platform_bot:
            platform = db.execute(select(Tenant).where(Tenant.company_code == PLATFORM_TENANT_CODE)).scalar_one_or_none()
            if platform:
                return {
                    "bot_token": get_tenant_config_value(db, platform.id, "telegram_bot_token"),
                    "chat_id": get_tenant_config_value(db, tenant_id, "telegram_chat_id"),
                }
    return {
        "bot_token": _tenant_value(db, tenant_id, "telegram_bot_token"),
        # A tenant without a configured chat must never inherit the global chat.
        "chat_id": get_tenant_config_value(db, tenant_id, "telegram_chat_id") if db is not None and tenant_id is not None else get_config_value("telegram_chat_id"),
    }


# -------------------- AI --------------------
def get_ai_config(db=None, tenant_id: int | None = None) -> dict:
    if db is not None:
        from sqlalchemy import select
        from app.core.models import PlatformAIConfig

        platform = db.execute(
            select(PlatformAIConfig).where(PlatformAIConfig.config_key == "platform")
        ).scalar_one_or_none()
        if platform and platform.enabled and platform.api_key:
            return {
                "model": platform.default_model or "minimax/minimax-m2.7",
                "api_key": platform.api_key,
                "endpoint": platform.endpoint,
            }
    return {
        "model": _tenant_value(db, tenant_id, "ai_model", "minimax/minimax-m2.7"),
        "api_key": _tenant_value(db, tenant_id, "ai_api_key"),
        "endpoint": None,
    }
