"""
catalog_app/services/agreement_service.py
────────────────────────────────────────────
Renders the Distribution & Consignment Agreement text shown to (and signed
by) applicants — server-side only.

Never trust client-submitted agreement text: an AuthorApplication's stored
snapshot must always be exactly what this function produces from the
application's own submitted data, so it stays trustworthy as proof of what
was actually agreed to. Used two ways:
  - Preview (before submission): render from an unsaved AuthorApplication +
    a list of unsaved AuthorApplicationBook instances, so the applicant sees
    the real, fully-populated agreement before signing.
  - Snapshot (at submission): render from the just-saved AuthorApplication,
    whose .books are now real rows — this is what gets stored as
    agreement_text_snapshot.
"""

from datetime import date

from django.template.loader import render_to_string

AGREEMENT_TEMPLATE = "catalog_app/agreements/distribution_consignment_v2.txt"

_PAYMENT_METHOD_LABELS = {
    "bank": "Bank Transfer",
    "mpesa_send": "M-Pesa — Send Money",
    "mpesa_paybill": "M-Pesa — PayBill",
    "mpesa_till": "M-Pesa — Till / Buy Goods",
}
_ACCOUNT_TYPE_LABELS = {"savings": "Savings", "current": "Current"}


def _payment_context(application) -> dict:
    method = application.payment_method or ""
    return {
        "method": method,
        "method_label": _PAYMENT_METHOD_LABELS.get(method, "Not yet selected"),
        "account_name": application.payment_account_name,
        "reference": application.payment_reference,
        "phone": application.payment_phone,
        "email": application.payment_email,
        "bank_name": application.bank_name,
        "bank_account_number": application.bank_account_number,
        "bank_branch": application.bank_branch,
        "bank_branch_code": application.bank_branch_code,
        "bank_account_type_label": _ACCOUNT_TYPE_LABELS.get(application.bank_account_type, ""),
        "bank_swift_code": application.bank_swift_code,
        "bank_address": application.bank_address,
        "recipient_address": application.recipient_address,
        "payment_currency": application.payment_currency,
        "paybill_number": application.paybill_number,
        "paybill_account_number": application.paybill_account_number,
        "till_number": application.till_number,
    }


def render_agreement(*, application, books=None, today=None) -> str:
    """
    application: an AuthorApplication instance — saved or unsaved. Must have
        .package set to a real DistributionPackage instance.
    books: iterable of AuthorApplicationBook-like objects (title, isbn,
        category, publication_year, selling_price_kes, copies_to_deliver).
        Defaults to application.books.all() — only valid if `application` is
        already saved (has a pk), since that's a real DB relation.
    """
    if books is None:
        books = application.books.all()

    package = application.package
    distributor_percent = package.my_keep_percent
    author_percent = 100 - distributor_percent
    # Only meaningful when allows_external_bookstores — the author's cut on
    # sales through bookstores other than Tai Bookstore, independent of
    # distributor_percent/author_percent above (which only ever govern Tai
    # Bookstore/website sales). None when the package doesn't allow it.
    external_author_percent = package.external_bookstore_author_percent if package.allows_external_bookstores else None

    book_rows = [
        {
            "title": b.title,
            "isbn": b.isbn,
            "genre": b.category.name if b.category_id and b.category else "",
            "publication_year": b.publication_year,
            "selling_price_kes": b.selling_price_kes,
            # Real Book instances (legacy-invitation flow — the book is
            # already in distribution, nothing left to deliver) have no such
            # field, unlike AuthorApplicationBook — default to None rather
            # than raising, and let the template show different wording.
            "copies_to_deliver": getattr(b, "copies_to_deliver", None),
        }
        for b in books
    ]

    context = {
        "today": today or date.today(),
        "author_name": application.full_name,
        "author_email": application.email,
        "author_phone": application.phone,
        "author_address": application.address,
        "author_id_number": application.id_number,
        "package": package,
        "distributor_percent": distributor_percent,
        "author_percent": author_percent,
        "external_author_percent": external_author_percent,
        "books": book_rows,
        "payment": _payment_context(application),
    }
    return render_to_string(AGREEMENT_TEMPLATE, context)
