from __future__ import annotations

from typing import Any

from config import settings


def _bool(v: Any, default: bool) -> bool:
    if isinstance(v, bool):
        return v
    if isinstance(v, str):
        return v.strip().lower() in {"1", "true", "yes", "on"}
    if v is None:
        return default
    return bool(v)


def get_mail_accounts() -> list[dict]:
    """
    Returns normalized account dictionaries.
    Falls back to legacy single-account config if MAIL_ACCOUNTS_JSON is empty.
    """
    configured = settings.mail_accounts
    normalized: list[dict] = []

    for idx, raw in enumerate(configured):
        if not isinstance(raw, dict):
            continue
        key = str(raw.get("key") or "").strip().lower()
        email = str(raw.get("email") or "").strip().lower()
        if not key or not email:
            continue
        normalized.append(
            {
                "key": key,
                "label": str(raw.get("label") or key.title()),
                "email": email,
                "imap_host": raw.get("imap_host") or settings.imap_host,
                "imap_port": int(raw.get("imap_port") or settings.imap_port or 993),
                "imap_username": raw.get("imap_username") or email,
                "imap_password": raw.get("imap_password") or settings.imap_password,
                "imap_use_ssl": _bool(raw.get("imap_use_ssl"), settings.imap_use_ssl),
                "imap_inbox": str(raw.get("imap_inbox") or "INBOX"),
                "imap_sent": str(raw.get("imap_sent") or "Sent"),
                "smtp_host": raw.get("smtp_host") or settings.smtp_host,
                "smtp_port": int(raw.get("smtp_port") or settings.smtp_port or 587),
                "smtp_username": raw.get("smtp_username") or email,
                "smtp_password": raw.get("smtp_password") or settings.smtp_password,
                "smtp_use_tls": _bool(raw.get("smtp_use_tls"), settings.smtp_use_tls),
                "sync_inbound": _bool(raw.get("sync_inbound"), True),
                "allow_send": _bool(raw.get("allow_send"), True),
            }
        )

    if normalized:
        return normalized

    # Legacy single-account fallback
    if settings.imap_host or settings.smtp_host:
        legacy_email = (settings.smtp_username or settings.imap_username or "").strip().lower()
        if legacy_email:
            return [
                {
                    "key": "default",
                    "label": "Default",
                    "email": legacy_email,
                    "imap_host": settings.imap_host,
                    "imap_port": settings.imap_port,
                    "imap_username": settings.imap_username,
                    "imap_password": settings.imap_password,
                    "imap_use_ssl": settings.imap_use_ssl,
                    "imap_inbox": "INBOX",
                    "imap_sent": "Sent",
                    "smtp_host": settings.smtp_host,
                    "smtp_port": settings.smtp_port,
                    "smtp_username": settings.smtp_username,
                    "smtp_password": settings.smtp_password,
                    "smtp_use_tls": settings.smtp_use_tls,
                    "sync_inbound": True,
                    "allow_send": True,
                }
            ]

    return []


def account_by_key(key: str | None) -> dict | None:
    k = (key or "").strip().lower()
    if not k:
        return None
    for acc in get_mail_accounts():
        if acc["key"] == k:
            return acc
    return None


def account_by_email(email_addr: str | None) -> dict | None:
    e = (email_addr or "").strip().lower()
    if not e:
        return None
    for acc in get_mail_accounts():
        if acc["email"] == e:
            return acc
    return None
