# retoor <retoor@molodetz.nl>

from __future__ import annotations

from dataclasses import dataclass
from typing import Any


def _as_int(value: Any, default: int) -> int:
    try:
        return int(value)
    except (TypeError, ValueError):
        return default


def _as_bool(value: Any) -> bool:
    if isinstance(value, bool):
        return value
    return str(value).strip().lower() in ("1", "true", "yes", "on")


@dataclass(frozen=True)
class EmailAccount:
    label: str
    imap_host: str
    imap_port: int
    imap_ssl: bool
    imap_starttls: bool
    smtp_host: str
    smtp_port: int
    smtp_ssl: bool
    smtp_starttls: bool
    username: str
    password: str
    from_address: str
    from_name: str

    @classmethod
    def from_row(cls, row: dict[str, Any]) -> "EmailAccount":
        username = str(row.get("username") or "")
        return cls(
            label=str(row.get("label") or ""),
            imap_host=str(row.get("imap_host") or ""),
            imap_port=_as_int(row.get("imap_port"), 993),
            imap_ssl=_as_bool(row.get("imap_ssl")),
            imap_starttls=_as_bool(row.get("imap_starttls")),
            smtp_host=str(row.get("smtp_host") or ""),
            smtp_port=_as_int(row.get("smtp_port"), 587),
            smtp_ssl=_as_bool(row.get("smtp_ssl")),
            smtp_starttls=_as_bool(row.get("smtp_starttls")),
            username=username,
            password=str(row.get("password") or ""),
            from_address=str(row.get("from_address") or username),
            from_name=str(row.get("from_name") or ""),
        )
