import io
from pptx import Presentation
from pptx.util import Inches, Pt, Emu
from pptx.dml.color import RGBColor
from pptx.enum.text import PP_ALIGN
from markupsafe import escape


def generate_pitch_deck(synthesis: dict, project_name: str, language: str = "ar") -> io.BytesIO:
    prs = Presentation()
    prs.slide_width = Inches(13.33)
    prs.slide_height = Inches(7.5)

    dark_bg = RGBColor(0x0F, 0x17, 0x2A)
    gold = RGBColor(0xD2, 0xAF, 0x20)
    white = RGBColor(0xFF, 0xFF, 0xFF)
    light_gray = RGBColor(0x94, 0xA3, 0xB8)

    def add_slide(title_text, bullets=None, subtitle=None):
        layout = prs.slide_layouts[6]
        slide = prs.slides.add_slide(layout)
        bg = slide.background
        fill = bg.fill
        fill.solid()
        fill.fore_color.rgb = dark_bg

        left = Inches(1)
        top = Inches(0.8)
        txBox = slide.shapes.add_textbox(left, top, Inches(11), Inches(1))
        tf = txBox.text_frame
        p = tf.paragraphs[0]
        p.text = str(title_text)
        p.font.size = Pt(36)
        p.font.bold = True
        p.font.color.rgb = gold

        if subtitle:
            txBox2 = slide.shapes.add_textbox(left, Inches(1.9), Inches(11), Inches(0.6))
            tf2 = txBox2.text_frame
            p2 = tf2.paragraphs[0]
            p2.text = str(subtitle)
            p2.font.size = Pt(16)
            p2.font.color.rgb = light_gray

        if bullets:
            content_top = Inches(2.8) if subtitle else Inches(2.2)
            txBox3 = slide.shapes.add_textbox(left, content_top, Inches(11), Inches(4.5))
            tf3 = txBox3.text_frame
            tf3.word_wrap = True
            for i, bullet in enumerate(bullets):
                p3 = tf3.add_paragraph() if i > 0 else tf3.paragraphs[0]
                p3.text = str(bullet)
                p3.font.size = Pt(18)
                p3.font.color.rgb = white
                p3.space_after = Pt(8)
        return slide

    # Slide 1: Title
    s1 = add_slide(str(project_name))
    txBox = s1.shapes.add_textbox(Inches(1), Inches(3), Inches(11), Inches(1))
    tf = txBox.text_frame
    p = tf.paragraphs[0]
    p.text = str(synthesis.get("executive_summary", "")[:200])
    p.font.size = Pt(18)
    p.font.color.rgb = light_gray
    tf.word_wrap = True

    verdict = synthesis.get("verdict", "N/A")
    vBox = s1.shapes.add_textbox(Inches(1), Inches(5.5), Inches(4), Inches(0.8))
    vf = vBox.text_frame
    vp = vf.paragraphs[0]
    vp.text = f"Verdict: {verdict}"
    vp.font.size = Pt(24)
    vp.font.bold = True
    vp.font.color.rgb = RGBColor(0x10, 0xB9, 0x81) if verdict == "GO" else (RGBColor(0xEF, 0x44, 0x44) if verdict == "NO-GO" else gold)

    # Slide 2: Problem / Opportunity
    add_slide(
        "Problem & Opportunity" if language == "en" else "المشكلة والفرصة",
        subtitle=str(synthesis.get("project_description", ""))[:200],
        bullets=[str(synthesis.get("verdict_explanation", ""))]
    )

    # Slide 3: Market Analysis + TAM/SAM/SOM
    tam = synthesis.get("tam_sam_som", {})
    market_bullets = [str(synthesis.get("market_analysis_summary", ""))[:300]]
    if isinstance(tam, dict):
        market_bullets.extend([
            f"TAM: {tam.get('tam_value', 'N/A')} - {tam.get('tam', '')}",
            f"SAM: {tam.get('sam_value', 'N/A')} - {tam.get('sam', '')}",
            f"SOM: {tam.get('som_value', 'N/A')} - {tam.get('som', '')}",
        ])
    add_slide("Market Size" if language == "en" else "حجم السوق", bullets=market_bullets)

    # Slide 4: Business Model
    bmc = synthesis.get("business_model_canvas", {})
    bmc_bullets = []
    if isinstance(bmc, dict):
        for key in ["value_propositions", "customer_segments", "revenue_streams", "channels"]:
            items = bmc.get(key, [])
            if isinstance(items, list) and items:
                bmc_bullets.append(f"{key.replace('_', ' ').title()}: {', '.join(str(i) for i in items[:3])}")
    add_slide("Business Model" if language == "en" else "نموذج العمل", bullets=bmc_bullets or ["N/A"])

    # Slide 5: GTM Strategy
    gtm = synthesis.get("gtm_strategy", {})
    gtm_bullets = []
    if isinstance(gtm, dict):
        for phase in ["phase1", "phase2", "phase3"]:
            val = gtm.get(phase, "")
            if val:
                gtm_bullets.append(f"{phase.upper()}: {str(val)[:150]}")
        pricing = gtm.get("pricing_strategy", "")
        if pricing:
            gtm_bullets.append(f"Pricing: {str(pricing)[:150]}")
    add_slide("Go-to-Market" if language == "en" else "استراتيجية دخول السوق", bullets=gtm_bullets or ["N/A"])

    # Slide 6: Financial Highlights
    fh = synthesis.get("financial_highlights", {})
    fin_bullets = []
    if isinstance(fh, dict):
        for key in ["estimated_startup_cost", "break_even", "roi_estimate", "year1_revenue", "year2_revenue", "year3_revenue"]:
            val = fh.get(key, "")
            if val:
                fin_bullets.append(f"{key.replace('_', ' ').title()}: {str(val)}")
    add_slide("Financials" if language == "en" else "التحليل المالي", bullets=fin_bullets or ["N/A"])

    # Slide 7: Competitive Landscape
    add_slide(
        "Competitive Analysis" if language == "en" else "التحليل التنافسي",
        bullets=[str(synthesis.get("competitive_analysis_summary", ""))[:400]]
    )

    # Slide 8: SWOT
    swot = synthesis.get("swot", {})
    swot_bullets = []
    if isinstance(swot, dict):
        for key in ["strengths", "weaknesses", "opportunities", "threats"]:
            items = swot.get(key, [])
            if isinstance(items, list) and items:
                swot_bullets.append(f"{key.title()}: {', '.join(str(i) for i in items[:2])}")
    add_slide("SWOT", bullets=swot_bullets or ["N/A"])

    # Slide 9: MVP
    mvp = synthesis.get("mvp_definition", {})
    mvp_bullets = []
    if isinstance(mvp, dict):
        core = mvp.get("core_features", [])
        if isinstance(core, list):
            mvp_bullets.extend([f"Core: {str(f)}" for f in core[:4]])
        timeline = mvp.get("estimated_timeline", "")
        cost = mvp.get("estimated_cost", "")
        if timeline:
            mvp_bullets.append(f"Timeline: {str(timeline)}")
        if cost:
            mvp_bullets.append(f"Cost: {str(cost)}")
    add_slide("MVP" if language == "en" else "المنتج الأولي", bullets=mvp_bullets or ["N/A"])

    # Slide 10: Risks
    risks = synthesis.get("risks_and_mitigations", [])
    risk_bullets = []
    if isinstance(risks, list):
        for r in risks[:5]:
            if isinstance(r, dict):
                risk_bullets.append(f"{r.get('risk', '')} [{r.get('severity', '')}] -> {r.get('mitigation', '')}")
    add_slide("Risks" if language == "en" else "المخاطر", bullets=risk_bullets or ["N/A"])

    # Slide 11: Final Verdict
    add_slide(
        "Conclusion" if language == "en" else "الخلاصة",
        bullets=[str(synthesis.get("final_verdict", ""))[:500]],
        subtitle=f"Confidence: {synthesis.get('confidence_score', 'N/A')}%"
    )

    buffer = io.BytesIO()
    prs.save(buffer)
    buffer.seek(0)
    return buffer
