"""
inventory/services/author_statement_service.py
──────────────────────────────────────────────
Emails an earnings statement (PDF attached) to an Author or Publisher —
either for a formal AuthorPayout batch, or an ad-hoc date-range statement
(optionally scoped to a single book title).
"""

import logging
from datetime import date

from django.conf import settings
from django.core.mail import EmailMessage

from inventory.services import pdf_service, report_service

logger = logging.getLogger(__name__)


def _format_period(start: date, end: date) -> str:
    """e.g. '1 January to 4 September 2026', or '28 December 2025 to 4 January 2026' across years."""
    if start.year == end.year:
        return f"{start.day} {start:%B} to {end.day} {end:%B} {end.year}"
    return f"{start.day} {start:%B} {start.year} to {end.day} {end:%B} {end.year}"


def send_author_statement_email(*, payee, start=None, end=None, book=None, payout=None) -> bool:
    """
    Send an earnings statement PDF by email to `payee` (an Author or Publisher).

    Pass `payout` for a formal AuthorPayout batch, or `start`/`end`
    (optionally with `book` to scope to one title) for an ad-hoc statement.
    Returns True if sent, False if the payee has no email or sending failed.
    """
    if not payee.email:
        return False

    if payout is not None:
        context = {"payout": payout}
        period_label = _format_period(payout.period_start, payout.period_end)
    else:
        detail = report_service.author_earnings_detail(payee, start, end, book=book)
        context = {"detail": detail}
        period_label = _format_period(start, end)

    pdf_bytes = pdf_service.render_pdf_bytes("inventory/pdf/author_statement.html", context)

    subject = f"Your TAI Afro Press Earnings Statement — {period_label}"
    body = (
        f"Dear {payee.name},\n\n"
        f"Please find attached your earnings statement for the period {period_label}.\n\n"
        "Thank you for trusting TAI AfroPress with the distribution of your titles. Kindly review "
        "and confirm the statement. Once confirmed, please send us an invoice for the amount due "
        "so we can proceed with payment.\n\n"
        "Please note that payment will be processed within 3–5 working days upon receipt and "
        "acceptance of the invoice.\n\n"
        "We appreciate your partnership and look forward to continuing to support the growth and "
        "reach of your titles.\n\n"
        "Best regards,\n"
        "Tai AfroPress\n"
        "Empowering African Stories for the World"
    )

    try:
        email = EmailMessage(
            subject=subject,
            body=body,
            from_email=settings.DEFAULT_FROM_EMAIL,
            to=[payee.email],
        )
        email.attach(f"statement-{payee.name.replace(' ', '-')}.pdf", pdf_bytes, "application/pdf")
        email.send(fail_silently=False)
        logger.info("Statement emailed: payee=%s period=%s", payee.name, period_label)
        return True
    except Exception:
        logger.exception("Failed to email statement for %s", payee.name)
        return False
