"""Odeslání e-mailu při novém termínu nebo změně ceny."""

from __future__ import annotations

import smtplib
import ssl
from email.message import EmailMessage


def _fmt_kc(n) -> str:
    try:
        return f"{int(round(float(n))):,}".replace(",", " ") + " Kč"
    except (TypeError, ValueError):
        return "—"


def _fmt_date(iso: str | None) -> str:
    if not iso:
        return "—"
    y, m, d = iso[:10].split("-")
    return f"{int(d)}. {int(m)}."


def build_message(events: list[dict]) -> tuple[str, str]:
    news = [e for e in events if e["type"] == "new"]
    prices = [e for e in events if e["type"] == "price"]
    parts = []
    if news:
        parts.append(f"{len(news)} nový termín" if len(news) == 1 else f"{len(news)} nové termíny")
    if prices:
        parts.append(f"{len(prices)} změna ceny" if len(prices) == 1 else f"{len(prices)} změny cen")
    subject = "Fischer přehled: " + ", ".join(parts)

    lines = ["Ahoj,", ""]
    if news:
        lines.append("Nové zájezdy z Pardubic (all inclusive, 2 osoby):")
        for e in news:
            o, h = e["offer"], e["hotel"]
            lines.append(
                f"- {h}: {_fmt_date(o['departure_date'])} → {_fmt_date(o['return_date'])} "
                f"({o.get('nights')} nocí) · {_fmt_kc(o['price_total'])} · {o.get('room') or o.get('meal')}"
            )
        lines.append("")
    if prices:
        lines.append("Změny cen:")
        for e in prices:
            o, h = e["offer"], e["hotel"]
            lines.append(
                f"- {h}: {_fmt_date(o['departure_date'])} → {_fmt_date(o['return_date'])} "
                f"{_fmt_kc(e['old_price'])} → {_fmt_kc(o['price_total'])}"
            )
        lines.append("")
    lines.append("Přehled zájezdů je na webu.")
    return subject, "\n".join(lines)


def send_events(cfg: dict, events: list[dict]) -> None:
    em = cfg.get("email") or {}
    if not events:
        return
    if not em.get("enabled"):
        print("E-mail: vypnuto (email.enabled=false)")
        return
    to_addr = (em.get("to") or "").strip()
    host = (em.get("smtp_host") or "").strip()
    if not to_addr or not host:
        print("E-mail: chybí email.to nebo email.smtp_host v config.json")
        return
    if host in {"smtp.example.com", "example.com"}:
        print("E-mail: v config.json doplň skutečný smtp_host, to a přihlášení")
        return

    subject, body = build_message(events)
    msg = EmailMessage()
    msg["Subject"] = subject
    msg["From"] = (em.get("from") or to_addr).strip()
    msg["To"] = to_addr
    msg.set_content(body)

    port = int(em.get("smtp_port") or 587)
    user = em.get("smtp_user") or ""
    password = em.get("smtp_password") or ""
    use_ssl = bool(em.get("smtp_ssl"))
    use_tls = em.get("smtp_tls", True) if not use_ssl else False

    context = ssl.create_default_context()
    if use_ssl:
        with smtplib.SMTP_SSL(host, port, timeout=30, context=context) as smtp:
            if user:
                smtp.login(user, password)
            smtp.send_message(msg)
    else:
        with smtplib.SMTP(host, port, timeout=30) as smtp:
            smtp.ehlo()
            if use_tls:
                smtp.starttls(context=context)
                smtp.ehlo()
            if user:
                smtp.login(user, password)
            smtp.send_message(msg)
    print(f"E-mail odeslán na {to_addr}: {subject}")
