# apps/wp_invoices_mail_app/renderers.py
from __future__ import annotations
from pathlib import Path
from typing import List, Dict, Any

from jinja2 import Environment, FileSystemLoader, select_autoescape

from shared.branding.branding import get_mail_theme


BASE_DIR = Path(__file__).resolve().parent
TEMPLATES_ROOT = BASE_DIR / "templates"  # .../apps/wp_invoices_mail_app/templates

print("FOLDER")
print(TEMPLATES_ROOT)
env = Environment(
    loader=FileSystemLoader(str(TEMPLATES_ROOT)),
    autoescape=select_autoescape(["html", "xml"]),
)


def _pick(node: Any) -> str:
    if isinstance(node, dict):
        return node.get("verbatim") or node.get("computed") or ""
    return node or ""


def _theme_context() -> dict:
    theme = get_mail_theme()
    return dict(
        font_stack=theme["font_stack"],
        page_bg=theme["page_bg"],
        card_bg=theme["card_bg"],
        border_color=theme["border_color"],
        brand_color=theme["brand_color"],
        text_color=theme["text_color"],
        secondary_text=theme["secondary_text"],
        success_color=theme["success_color"],
        error_color=theme["error_color"],
        stat_bg=theme["stat_bg"],
        table_header_bg=theme["table_header_bg"],
        tag_bg=theme["tag_bg"],
        tag_text=theme["tag_text"],
    )


# 4.1 – RESULTADOS (ya existente, lo dejo aquí por completitud)
def render_results_email_html(results: List[Dict[str, Any]]) -> str:
    theme_ctx = _theme_context()
    template = env.get_template("v1/email_results.html")

    total = len(results)
    n_ok = sum(1 for r in results if r.get("ok", True) and not r.get("error"))
    n_err = total - n_ok

    if not results:
        intro_html = (
            "We received your email but could not process any valid invoice.<br/>"
            "Please make sure the attachments are clear invoice images or PDF files."
        )
    else:
        if total == 1:
            intro_html = "We processed the attached invoice and here is the result:"
        else:
            intro_html = (
                f"We processed <strong>{total}</strong> attached invoices. "
                "Here is a quick summary:"
            )

    results_view: list[dict[str, Any]] = []
    for idx, r in enumerate(results, start=1):
        fname = r.get("filename") or r.get("original_filename") or "(no filename)"
        ok_flag = r.get("ok", True)
        error_msg = r.get("error")

        if not ok_flag or error_msg:
            status_label = "Not processed"
            details = [f"Reason: {error_msg or 'Unknown error.'}"]
        else:
            extracted = r.get("extracted") or {}
            header = extracted.get("header", {}) or {}
            supplier = header.get("supplier", {}) or {}
            invoice_block = header.get("invoice", {}) or {}
            totals = extracted.get("totals", {}) or {}

            supplier_name = _pick(supplier.get("name"))
            invoice_number = _pick(invoice_block.get("number"))
            issue_date = _pick((invoice_block.get("date") or {}).get("issue_date"))
            grand_total = _pick(totals.get("grand_total"))
            currency = totals.get("currency") or "AUD"

            details: list[str] = []
            if supplier_name:
                details.append(f"Supplier: <strong>{supplier_name}</strong>")
            if invoice_number:
                details.append(f"Invoice #: {invoice_number}")
            if issue_date:
                details.append(f"Date: {issue_date}")
            if grand_total:
                details.append(f"Total: {grand_total} {currency}")
            if not details:
                details.append("Extracted successfully.")

            status_label = "Processed"

        results_view.append(
            {
                "index": idx,
                "filename": fname,
                "status": status_label,
                "details": details,
            }
        )

    footer_note = (
        "If something looks wrong, please double-check the original supplier invoice. "
        "The system may have doubts in low-quality or partially readable areas."
        "<br/><br/>"
        "Review PDFs are attached for every invoice processed successfully. "
        "Invoices marked as “Not processed” will not have a review PDF."
    )

    return template.render(
        **theme_ctx,
        intro_html=intro_html,
        show_stats=bool(results),
        n_ok=n_ok,
        n_err=n_err,
        results_view=results_view,
        footer_note=footer_note,
    )


# 4.2 – HTML para credenciales inválidas
def render_invalid_credentials_html(auth_msg: str | None = None) -> str:
    theme_ctx = _theme_context()
    template = env.get_template("v1/email_message.html")

    subject = "Invoice Bot – Authentication problem"
    tag_label = "Auth error"

    intro_html = (
        "We could not process your email because there was a problem "
        "with the login credentials in the message body."
    )

    paragraphs: list[str] = [
        "Please make sure you include a valid login in the body of the email "
        "using this format:",
        "<code>USER: your_username<br/>PASS: your_password</code>",
        "If the credentials are incorrect, the bot will ignore the message "
        "and no invoices will be processed.",
    ]

    if auth_msg:
        paragraphs.append(
            f"<small>Technical detail: {auth_msg}</small>"
        )

    footer_note = (
        "Once your login is correct, send the invoice again as an attachment "
        "(PDF or clear image) and you will receive a processing summary email."
    )

    return template.render(
        **theme_ctx,
        subject=subject,
        tag_label=tag_label,
        intro_html=intro_html,
        paragraphs=paragraphs,
        footer_note=footer_note,
    )


# 4.3 – HTML para “sin adjuntos válidos”
def render_no_attachments_html(inline_photos: bool) -> str:
    theme_ctx = _theme_context()
    template = env.get_template("v1/email_message.html")

    subject = "Invoice Bot – No valid attachments found"
    tag_label = "No attachments"

    intro_html = (
        "We received your email but could not find any valid invoice attachments."
    )

    paragraphs: list[str] = []

    if inline_photos:
        paragraphs.append(
            "It looks like you inserted a photo inside the email body. "
            "To process it, please attach the invoice as a file using the "
            "paper-clip icon instead of pasting it into the message text."
        )
    else:
        paragraphs.append(
            "Please attach at least one invoice as a PDF or a clear image file "
            "(JPG, PNG, etc.) so the bot can process it."
        )

    paragraphs.append(
        "This message has not been processed and no review PDF has been generated."
    )

    footer_note = (
        "As soon as you send an email with valid attachments, "
        "the bot will reply with a processing summary and a review PDF per invoice."
    )

    return template.render(
        **theme_ctx,
        subject=subject,
        tag_label=tag_label,
        intro_html=intro_html,
        paragraphs=paragraphs,
        footer_note=footer_note,
    )
