"""Exportação da apresentação HTML da síntese (Reveal.js) — RSL completa."""

from __future__ import annotations

import re
from io import BytesIO

from django.template.loader import render_to_string



def _bullets_from_text(text: str, max_items: int = 8) -> list[str]:
    if not text:
        return []
    parts = re.split(r"\n\n+|\n(?=[•\-*])", text.strip())
    items = []
    for p in parts:
        p = re.sub(r"^[•\-\*]\s*", "", p.strip())
        if len(p) > 20:
            items.append(p[:400] + ("…" if len(p) > 400 else ""))
        if len(items) >= max_items:
            break
    return items


def build_presentation_slides(review, package: dict) -> dict:
    """Estrutura rica para apresentação acadêmica de RSL."""
    sections = package.get("sections", {})
    return {
        "title": review.title,
        "objective": review.objective or package.get("picoc", {}).get("objective") or "",
        "picoc": package.get("picoc", {}),
        "questions": package.get("questions", []),
        "hypotheses": package.get("hypotheses", []),
        "hypotheses_strong": package.get("hypotheses_strong", []),
        "hypotheses_weak": package.get("hypotheses_weak", []),
        "rq_coverage": package.get("rq_coverage", []),
        "hypothesis_evidence": package.get("hypothesis_evidence", []),
        "inclusion": package.get("inclusion", []),
        "exclusion": package.get("exclusion", []),
        "keywords": package.get("keywords", [])[:12],
        "protocol": package.get("protocol_snapshot", {}),
        "funnel": package.get("funnel", {}),
        "quality_studies": package.get("quality_summary", {}),
        "review_quality": package.get("review_quality_assessment", {}),
        "n_final": package.get("meta", {}).get("n_final", 0),
        "summary_table": package.get("summary_table", []),
        "summary_chunks": [
            package.get("summary_table", [])[i : i + 10]
            for i in range(0, len(package.get("summary_table", [])), 10)
        ],
        "frequency_tables": package.get("frequency_tables", []),
        "crosstabs": package.get("crosstabs", []),
        "gaps": package.get("gaps", []),
        "limitations": package.get("limitations", [])[:12],
        "methodological_lacunas": package.get("methodological_lacunas", []),
        "year_distribution": package.get("year_distribution", []),
        "source_distribution": package.get("source_distribution", []),
        "key_findings": package.get("key_findings", []),
        "fill_rates": package.get("fill_rates", [])[:8],
        "resumo_bullets": _bullets_from_text(sections.get("resumo_executivo", ""), 6),
        "sintese_bullets": _bullets_from_text(sections.get("sintese_tematica", ""), 6),
        "discussao_bullets": _bullets_from_text(sections.get("discussao", ""), 6),
        "lacunas_lit_bullets": _bullets_from_text(sections.get("lacunas_literatura", ""), 5),
        "conclusao_bullets": _bullets_from_text(sections.get("conclusao", ""), 5),
        "generated_at": package.get("meta", {}).get("generated_at", ""),
    }


def export_synthesis_presentation_html(review, package: dict) -> BytesIO:
    slides = build_presentation_slides(review, package)
    html_content = render_to_string(
        "reporting/synthesis_presentation.html",
        {
            "review": review,
            "slides": slides,
            "package": package,
        },
    )
    buf = BytesIO(html_content.encode("utf-8"))
    buf.seek(0)
    return buf


def presentation_download_name(review) -> str:
    return f"{review.slug}-apresentacao-rsl.html"
