"""Load active email account from PostgreSQL for tools-api."""

from __future__ import annotations

import os
from typing import Any

from app.db import fetch_one


def get_active_email_config() -> dict[str, Any]:
    """Return SMTP config: DB active account first, then env fallback."""
    try:
        row = fetch_one(
            """
            SELECT id, label, email_address, provider, smtp_host, smtp_port,
                   smtp_user, smtp_password, imap_host, imap_port, imap_user, imap_password
            FROM email_accounts WHERE is_active = TRUE
            ORDER BY updated_at DESC LIMIT 1
            """
        )
        if row and row.get("smtp_host"):
            return {
                "source": "database",
                "account_id": row.get("id"),
                "label": row.get("label"),
                "smtp_host": (row.get("smtp_host") or "").strip(),
                "smtp_port": int(row.get("smtp_port") or 587),
                "smtp_user": (row.get("smtp_user") or row.get("email_address") or "").strip(),
                "smtp_pass": row.get("smtp_password") or "",
                "smtp_from": (row.get("email_address") or row.get("smtp_user") or "").strip(),
            }
    except Exception:
        pass

    smtp_user = os.getenv("SMTP_USER", "").strip()
    return {
        "source": "env",
        "account_id": None,
        "label": "Environment",
        "smtp_host": os.getenv("SMTP_HOST", "").strip(),
        "smtp_port": int(os.getenv("SMTP_PORT", "587")),
        "smtp_user": smtp_user,
        "smtp_pass": os.getenv("SMTP_PASS", "").strip(),
        "smtp_from": os.getenv("SMTP_FROM", smtp_user).strip(),
    }
