"""
Génération du Pitch Deck en PowerPoint (.pptx).
Template soigné (thème emerald), 13 slides alignées sur PItchcomplet.md.
L'utilisateur peut ajouter transitions et animations dans PowerPoint après ouverture.
"""
import io
from pptx import Presentation
from pptx.util import Inches, Pt
from pptx.dml.color import RGBColor
from pptx.enum.text import PP_ALIGN, MSO_ANCHOR
from pptx.enum.shapes import MSO_SHAPE

# Thème Sénégal Academy (emerald)
RGB_TITLE = RGBColor(0x04, 0x78, 0x57)   # #047857
RGB_ACCENT = RGBColor(0x06, 0x5f, 0x46)  # #065f46
RGB_LIGHT = RGBColor(0xd1, 0xfa, 0xe5)  # #d1fae5
RGB_GREY = RGBColor(0x6b, 0x72, 0x80)


def _get_attr(pitch_data, name, default=""):
    v = getattr(pitch_data, name, None)
    if v is None:
        return default
    s = str(v).strip()
    return s if s else default


def generate_pitch_pptx_file(pitch_data):
    """
    Génère un fichier PowerPoint du Pitch Deck (13 slides).
    Retourne un BytesIO contenant le .pptx.
    """
    prs = Presentation()
    prs.slide_width = Inches(13.333)
    prs.slide_height = Inches(7.5)

    def _add_title_slide(title, subtitle=None):
        """Slide avec grand titre (layout 6 = blank)."""
        blank = prs.slide_layouts[6]
        slide = prs.slides.add_slide(blank)
        # Fond discret
        left = Inches(0.5)
        top = Inches(2.2)
        width = prs.slide_width - Inches(1)
        height = Inches(1.8)
        box = slide.shapes.add_textbox(left, top, width, height)
        tf = box.text_frame
        tf.word_wrap = True
        p = tf.paragraphs[0]
        p.text = title[:200]
        p.font.size = Pt(32)
        p.font.bold = True
        p.font.color.rgb = RGB_TITLE
        p.alignment = PP_ALIGN.CENTER
        if subtitle:
            p2 = tf.add_paragraph()
            p2.text = subtitle[:300]
            p2.font.size = Pt(14)
            p2.font.color.rgb = RGB_GREY
            p2.alignment = PP_ALIGN.CENTER
            p2.space_before = Pt(12)
        # Pied de page
        footer = slide.shapes.add_textbox(Inches(0.5), prs.slide_height - Inches(0.6), Inches(12), Inches(0.4))
        footer.text_frame.paragraphs[0].text = "Sénégal Academy — Pitch Deck"
        footer.text_frame.paragraphs[0].font.size = Pt(9)
        footer.text_frame.paragraphs[0].font.color.rgb = RGB_GREY
        return slide

    def _add_content_slide(slide_title, content):
        """Slide titre + corps de texte."""
        blank = prs.slide_layouts[6]
        slide = prs.slides.add_slide(blank)
        # Titre
        title_box = slide.shapes.add_textbox(Inches(0.6), Inches(0.5), Inches(12), Inches(1))
        tf = title_box.text_frame
        tf.word_wrap = True
        p = tf.paragraphs[0]
        p.text = slide_title[:150]
        p.font.size = Pt(24)
        p.font.bold = True
        p.font.color.rgb = RGB_TITLE
        # Ligne sous le titre (optionnel)
        line = slide.shapes.add_shape(
            MSO_SHAPE.RECTANGLE, Inches(0.6), Inches(1.35), Inches(1), Inches(0.03)
        )
        line.fill.solid()
        line.fill.fore_color.rgb = RGB_ACCENT
        line.line.fill.background()
        # Contenu
        body = (content or "").strip() or "—"
        body_box = slide.shapes.add_textbox(Inches(0.6), Inches(1.6), Inches(12), Inches(5.2))
        body_tf = body_box.text_frame
        body_tf.word_wrap = True
        body_tf.auto_size = None
        for i, para in enumerate(body.split("\n")[:30]):
            if not para.strip():
                continue
            p = body_tf.paragraphs[0] if i == 0 else body_tf.add_paragraph()
            p.text = para[:500]
            p.font.size = Pt(12)
            p.font.color.rgb = RGBColor(0x1f, 0x29, 0x3b)
            p.space_after = Pt(6)
        # Pied de page
        footer = slide.shapes.add_textbox(Inches(0.5), prs.slide_height - Inches(0.6), Inches(12), Inches(0.4))
        footer.text_frame.paragraphs[0].text = "Sénégal Academy — Pitch Deck"
        footer.text_frame.paragraphs[0].font.size = Pt(9)
        footer.text_frame.paragraphs[0].font.color.rgb = RGB_GREY
        return slide

    # Slide 1 : Titre + promoteur / tagline
    project_name = _get_attr(pitch_data, "project_name", "Pitch Deck")
    subtitle = _get_attr(pitch_data, "promoter_presentation") or _get_attr(pitch_data, "tagline", "Présentation")
    _add_title_slide(project_name, subtitle)

    # Slides 2–12 : contenu
    slides_content = [
        ("Description du projet", _get_attr(pitch_data, "project_description")),
        ("Quel problème votre projet cherche-t-il à résoudre ?", _get_attr(pitch_data, "problem")),
        ("Quelle solution innovante ou valeur ajoutée votre projet propose-t-il ?", _get_attr(pitch_data, "solution")),
        ("Les clients potentiels", _get_attr(pitch_data, "market_potential")),
        ("Modèle économique", _get_attr(pitch_data, "business_model")),
        ("Vos réalisations (en écrit)", _get_attr(pitch_data, "achievements_text")),
        ("Vos réalisations (en image)", _slide_images(pitch_data)),
        ("Vos prochaines étapes", _get_attr(pitch_data, "roadmap")),
        ("Vos besoins", _get_attr(pitch_data, "needs")),
        ("Votre vision d'ici 5 ans", _get_attr(pitch_data, "vision_5_years")),
        ("Un dernier mot pour convaincre le jury ou l'audience ?", _get_attr(pitch_data, "final_pitch")),
    ]
    for title, content in slides_content:
        _add_content_slide(title, content)

    # Slide 13 : Remerciements
    blank = prs.slide_layouts[6]
    slide = prs.slides.add_slide(blank)
    box = slide.shapes.add_textbox(Inches(1), Inches(2.8), Inches(11.3), Inches(1.5))
    tf = box.text_frame
    tf.paragraphs[0].text = "Merci de votre aimable attention"
    tf.paragraphs[0].font.size = Pt(28)
    tf.paragraphs[0].font.bold = True
    tf.paragraphs[0].font.color.rgb = RGB_TITLE
    tf.paragraphs[0].alignment = PP_ALIGN.CENTER
    p2 = tf.add_paragraph()
    p2.text = "Invitation aux questions du jury"
    p2.font.size = Pt(14)
    p2.font.color.rgb = RGB_GREY
    p2.alignment = PP_ALIGN.CENTER
    p2.space_before = Pt(14)
    footer = slide.shapes.add_textbox(Inches(0.5), prs.slide_height - Inches(0.6), Inches(12), Inches(0.4))
    footer.text_frame.paragraphs[0].text = "Sénégal Academy — Pitch Deck"
    footer.text_frame.paragraphs[0].font.size = Pt(9)
    footer.text_frame.paragraphs[0].font.color.rgb = RGB_GREY

    buffer = io.BytesIO()
    prs.save(buffer)
    buffer.seek(0)
    return buffer


def _slide_images(pitch_data):
    """Texte pour la slide réalisations (images) : légendes ou message par défaut."""
    try:
        images_attr = getattr(pitch_data, "images", None)
        images = list(images_attr.all()[:6]) if images_attr is not None else []
    except Exception:
        images = []
    if not images:
        return "— Aucune image ajoutée —"
    lines = []
    for img in images:
        cap = getattr(img, "caption", None) or "Image de réalisation"
        lines.append(str(cap)[:200])
    return "\n".join(lines)
