"""
catalog_app/services/legacy_invitation_service.py
───────────────────────────────────────────────────
Retroactive agreement flow for authors who already have books in the
catalog (added by staff before the self-service application feature
existed). Mirrors author_application_service.py's maker-checker shape, but
approving here UPDATES the existing Author/Book rows rather than creating
new ones — see LegacyAuthorInvitation's docstring in models.py.
"""

import logging
from dataclasses import dataclass
from datetime import timedelta
from decimal import Decimal
from typing import Optional

from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.utils import timezone

from catalog_app.models import LegacyAuthorInvitation, PaymentDetailsMixin
from catalog_app.services.agreement_service import render_agreement

logger = logging.getLogger(__name__)

TOKEN_VALIDITY = timedelta(days=30)

_PAYMENT_FIELD_NAMES = [f.name for f in PaymentDetailsMixin._meta.get_fields()]


class _LegacyAgreementView:
    """
    Adapts a LegacyAuthorInvitation to the attribute shape
    agreement_service.render_agreement() expects from an AuthorApplication.
    Identity (name/email) comes from the linked Author, since that doesn't
    change at signing time; everything else (address, id_number, package,
    payment fields) comes from the invitation itself — what's actually being
    confirmed/updated by this signing.
    """
    def __init__(self, invitation: LegacyAuthorInvitation):
        self._invitation = invitation
        self._author = invitation.author

    @property
    def full_name(self):
        return self._author.name

    @property
    def email(self):
        return self._author.email

    @property
    def phone(self):
        return ""  # Author has no phone field

    def __getattr__(self, name):
        return getattr(self._invitation, name)


@dataclass
class _EffectiveBook:
    """Book × any pending LegacyInvitationBookEdit, merged — what the agreement
    text (and the signing wizard, on reload) should show: the requested new
    title/cover/price if the author asked for one, else the book's current
    value. copies_to_deliver is always None here (see
    agreement_service.render_agreement). id/cover/has_pending_edit exist for
    the API response, not the agreement template."""
    id: int
    title: str
    isbn: str
    category: Optional[object]
    category_id: Optional[int]
    publication_year: Optional[int]
    selling_price_kes: Optional[Decimal]
    cover: object
    has_pending_edit: bool
    copies_to_deliver: None = None


def effective_books(invitation: LegacyAuthorInvitation) -> list:
    """invitation.books.all(), each overlaid with its pending edit (if any) — title/cover/price
    the author asked to change while signing, not yet applied to the real Book."""
    edits = {e.book_id: e for e in invitation.book_edits.all()}
    result = []
    for book in invitation.books.all():
        edit = edits.get(book.pk)
        result.append(_EffectiveBook(
            id=book.pk,
            title=(edit.title if edit and edit.title else book.title),
            isbn=book.isbn,
            category=book.category,
            category_id=book.category_id,
            publication_year=book.publication_year,
            # book.selling_price_kes can be None for a book that only ever
            # had a general price set (never an explicit one) — fall back
            # to that, same convention as Book.effective_price, so neither
            # the agreement text nor the signing form shows a blank gap.
            selling_price_kes=(
                edit.selling_price_kes if edit and edit.selling_price_kes is not None
                else (book.selling_price_kes if book.selling_price_kes is not None else book.price)
            ),
            cover=(edit.cover if edit and edit.cover else book.cover),
            has_pending_edit=bool(edit and (edit.title or edit.cover or edit.selling_price_kes is not None)),
        ))
    return result


def render_legacy_agreement(*, invitation: LegacyAuthorInvitation, books=None, today=None) -> str:
    """
    books: defaults to effective_books(invitation) (current book data
    overlaid with any pending edits the author made while signing) — pass an
    override only if invitation isn't saved yet (not needed today since
    books are fixed by staff at creation, but kept symmetrical with
    render_agreement's preview/snapshot duality).
    """
    if books is None:
        books = effective_books(invitation)
    return render_agreement(application=_LegacyAgreementView(invitation), books=books, today=today)


def create_invitation(*, author, books, user=None) -> LegacyAuthorInvitation:
    """Create a draft invitation for an existing author + existing book(s). Does not send anything yet."""
    invitation = LegacyAuthorInvitation.objects.create(author=author, created_by=user)
    invitation.books.set(books)
    return invitation


def send_invitation_email(invitation: LegacyAuthorInvitation) -> bool:
    """
    (Re)send the signing-link email — rotates the token and resets the
    30-day expiry each time, so a resend also invalidates any previously
    leaked/expired link. Returns True if sent.
    """
    author = invitation.author
    if not author.email:
        logger.warning("send_invitation_email: author #%d has no email.", author.pk)
        return False

    import uuid
    invitation.token = uuid.uuid4()
    invitation.sent_at = timezone.now()
    invitation.expires_at = invitation.sent_at + TOKEN_VALIDITY
    if invitation.status == LegacyAuthorInvitation.STATUS_DRAFT:
        invitation.status = LegacyAuthorInvitation.STATUS_SENT
    invitation.save(update_fields=["token", "sent_at", "expires_at", "status"])

    site = getattr(settings, "PUBLIC_STORE_URL", "") or getattr(settings, "SITE_URL", "")
    sign_url = f"{site.rstrip('/')}/distribute/legacy/{invitation.token}/"
    book_titles = ", ".join(invitation.books.values_list("title", flat=True))

    subject = "Action needed: sign your Tai AfroPress Distribution Agreement"
    context = {"invitation": invitation, "author": author, "sign_url": sign_url, "book_titles": book_titles}
    html_body = render_to_string("catalog_app/email/legacy_invitation_sent.html", context)
    text_body = (
        f"Dear {author.name},\n\n"
        f"Tai AfroPress already distributes the following title(s) of yours: {book_titles}.\n\n"
        f"To formalize this under a signed Distribution & Consignment Agreement, please choose "
        f"a distribution package and confirm your details at the link below:\n\n"
        f"{sign_url}\n\n"
        f"This link is valid for 30 days.\n\n"
        f"Best regards,\n"
        f"Tai AfroPress\n"
        f"Empowering African Stories for the World"
    )

    try:
        email = EmailMultiAlternatives(
            subject=subject, body=text_body,
            from_email=settings.DEFAULT_FROM_EMAIL, to=[author.email],
        )
        email.attach_alternative(html_body, "text/html")
        email.send(fail_silently=False)
        logger.info("Legacy invitation emailed: invitation=%d author=%s", invitation.pk, author.name)
        return True
    except Exception:
        logger.exception("Failed to email legacy invitation #%d", invitation.pk)
        return False


def approve_invitation(*, invitation: LegacyAuthorInvitation, user=None):
    """
    Update the existing Author with the confirmed profile/payment details
    and the chosen package's margin (applies to ALL of this author's books
    going forward, not just the ones in this invitation — a deliberate
    policy choice, not a per-book override). Existing SaleItem rows already
    have their own margin snapshot from when they were recorded, so past
    sales are unaffected by this change.
    """
    if invitation.status != LegacyAuthorInvitation.STATUS_SUBMITTED:
        raise ValueError(f"Invitation is not awaiting review (current: {invitation.get_status_display()}).")
    if invitation.package_id is None:
        raise ValueError("No package was selected.")

    author = invitation.author
    author.bio = invitation.bio
    author.address = invitation.address
    author.id_number = invitation.id_number
    for name in _PAYMENT_FIELD_NAMES:
        setattr(author, name, getattr(invitation, name))
    author.default_my_keep_percent = invitation.package.my_keep_percent
    author.save()

    for edit in invitation.book_edits.select_related("book"):
        book = edit.book
        changed = []
        if edit.title:
            book.title = edit.title
            changed.append("title")
        if edit.cover:
            book.cover = edit.cover
            changed.append("cover")
        if edit.selling_price_kes is not None:
            book.selling_price_kes = edit.selling_price_kes
            changed.append("selling_price_kes")
        if changed:
            book.save(update_fields=changed)

    invitation.status = LegacyAuthorInvitation.STATUS_APPROVED
    invitation.reviewed_by = user
    invitation.reviewed_at = timezone.now()
    invitation.save(update_fields=["status", "reviewed_by", "reviewed_at"])

    return author


def reject_invitation(*, invitation: LegacyAuthorInvitation, reason: str, user=None) -> LegacyAuthorInvitation:
    if invitation.status != LegacyAuthorInvitation.STATUS_SUBMITTED:
        raise ValueError(f"Invitation is not awaiting review (current: {invitation.get_status_display()}).")

    invitation.status = LegacyAuthorInvitation.STATUS_REJECTED
    invitation.rejection_reason = reason
    invitation.reviewed_by = user
    invitation.reviewed_at = timezone.now()
    invitation.save(update_fields=["status", "rejection_reason", "reviewed_by", "reviewed_at"])
    return invitation
