"""
Reports domain: email-gated PDF market intelligence reports.

Flow:
  GET  /<lang>/reports/<slug>          → landing page with teaser + email form
  POST /<lang>/reports/<slug>          → capture email → re-render with download button
  GET  /<lang>/reports/<slug>/download → serve pre-built PDF
"""

import logging
from pathlib import Path

from quart import Blueprint, Response, abort, g, render_template, request

from ..core import capture_waitlist_email, csrf_protect
from ..i18n import get_translations

logger = logging.getLogger(__name__)

bp = Blueprint(
    "reports",
    __name__,
    template_folder=str(Path(__file__).parent / "templates"),
    url_prefix="/reports",
)

# Registry of available reports.  Key = slug, value = per-lang PDF filenames.
# PDFs live in data/content/reports/_build/<filename>.
REPORT_REGISTRY: dict[str, dict[str, str]] = {
    "q1-2026": {
        "en": "state-of-padel-q1-2026-en.pdf",
        "de": "state-of-padel-q1-2026-de.pdf",
        "title_en": "State of Padel Q1 2026: Global Market Report",
        "title_de": "State of Padel Q1 2026: Weltmarktbericht",
    },
}

_BUILD_DIR = Path(__file__).parent.parent.parent.parent.parent / "data" / "content" / "reports" / "_build"


def _get_report(slug: str) -> dict | None:
    return REPORT_REGISTRY.get(slug)


def _pdf_path(slug: str, lang: str) -> Path | None:
    report = _get_report(slug)
    if not report:
        return None
    filename = report.get(lang) or report.get("en")
    if not filename:
        return None
    return _BUILD_DIR / filename


@bp.get("/<slug>")
async def landing(slug: str) -> str:
    """Report landing page with teaser stats and email capture form."""
    report = _get_report(slug)
    if not report:
        abort(404)
    lang = g.get("lang", "en")
    t = get_translations(lang)
    title = report.get(f"title_{lang}") or report.get("title_en", "")
    return await render_template(
        "reports/report_landing.html",
        slug=slug,
        report=report,
        title=title,
        lang=lang,
        t=t,
        confirmed=False,
    )


@bp.post("/<slug>")
@csrf_protect
async def capture(slug: str) -> str:
    """Capture email and re-render with download button."""
    report = _get_report(slug)
    if not report:
        abort(404)
    lang = g.get("lang", "en")
    t = get_translations(lang)
    title = report.get(f"title_{lang}") or report.get("title_en", "")

    form = await request.form
    email = (form.get("email") or "").strip().lower()
    if email:
        await capture_waitlist_email(email, intent="report", plan=slug)

    return await render_template(
        "reports/report_landing.html",
        slug=slug,
        report=report,
        title=title,
        lang=lang,
        t=t,
        confirmed=bool(email),
    )


@bp.get("/<slug>/download")
async def download(slug: str) -> Response:
    """Serve pre-built PDF for a given report slug and language."""
    report = _get_report(slug)
    if not report:
        abort(404)
    lang = g.get("lang", "en")
    pdf_path = _pdf_path(slug, lang)
    if not pdf_path or not pdf_path.exists():
        abort(404)

    pdf_bytes = pdf_path.read_bytes()
    filename = pdf_path.name
    return Response(
        pdf_bytes,
        mimetype="application/pdf",
        headers={"Content-Disposition": f'inline; filename="{filename}"'},
    )
