import json
import subprocess
import os
import fitz

with open('scratch/parsed_blocks.json', 'r', encoding='utf-8') as f:
    pages_data = json.load(f)

def escape_html(text):
    return text.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('"', '&quot;')

html_pages = []

# CSS Styles
css = """
@page {
    size: 297mm 210mm;
    margin: 0;
}
* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}
body {
    font-family: 'Segoe UI', -apple-system, BlinkMacSystemFont, Roboto, Helvetica, Arial, sans-serif;
    background-color: #f1f5f9;
    color: #0f172a;
    -webkit-print-color-adjust: exact;
    print-color-adjust: exact;
}

.page {
    width: 297mm;
    height: 210mm;
    max-height: 210mm;
    overflow: hidden;
    page-break-after: always;
    break-after: page;
    background: #ffffff;
    padding: 13mm 18mm 11mm 18mm;
    display: flex;
    flex-direction: column;
    position: relative;
}

/* Header */
.top-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 2px solid #e2e8f0;
    padding-bottom: 7px;
    margin-bottom: 12px;
    flex-shrink: 0;
}
.show-title {
    font-size: 13px;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 1.5px;
    color: #b45309; /* amber/obrador warm tone */
    display: flex;
    align-items: center;
    gap: 8px;
}
.show-title::before {
    content: '';
    display: inline-block;
    width: 10px;
    height: 10px;
    background: #d97706;
    border-radius: 50%;
}
.show-guests {
    font-size: 12.5px;
    color: #475569;
    font-weight: 500;
}
.page-badge {
    background: #0f172a;
    color: #ffffff;
    font-size: 12px;
    font-weight: 700;
    padding: 3px 12px;
    border-radius: 20px;
    letter-spacing: 0.8px;
}

/* Block Title */
.block-header {
    margin-bottom: 12px;
    flex-shrink: 0;
}
.block-title {
    font-weight: 800;
    color: #0f172a;
    line-height: 1.15;
    letter-spacing: -0.3px;
    display: flex;
    align-items: baseline;
    gap: 10px;
}

/* Question Content Container */
.content-area {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    min-height: 0;
}

/* Main Question Card */
.main-card {
    background: #f8fafc;
    border: 2px solid #cbd5e1;
    border-left: 7px solid #d97706; /* Amber highlight */
    border-radius: 10px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.03);
    flex-shrink: 0;
}
.main-card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-bottom: 6px;
    margin-bottom: 6px;
    border-bottom: 1px dashed #cbd5e1;
}
.main-badge {
    background: #d97706;
    color: #ffffff;
    font-size: 11px;
    font-weight: 800;
    text-transform: uppercase;
    letter-spacing: 1px;
    padding: 3px 9px;
    border-radius: 4px;
    display: inline-block;
}
.main-card-body {
    display: flex;
    gap: 12px;
    align-items: flex-start;
}
.main-q-num {
    background: #0f172a;
    color: #ffffff;
    font-weight: 800;
    border-radius: 6px;
    flex-shrink: 0;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
}
.main-q-text {
    font-weight: 700;
    color: #0f172a;
}

/* Repreguntas Section */
.repreguntas-section {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: 0;
    margin-top: 10px;
}
.repreguntas-label {
    font-size: 11px;
    font-weight: 800;
    text-transform: uppercase;
    letter-spacing: 1.2px;
    color: #64748b;
    margin-bottom: 8px;
    display: flex;
    align-items: center;
    gap: 6px;
    flex-shrink: 0;
}
.repreguntas-label::after {
    content: '';
    flex: 1;
    height: 1px;
    background: #e2e8f0;
}
.repreguntas-grid {
    flex: 1;
    display: grid;
    gap: 10px;
    min-height: 0;
}

/* Individual Repregunta Card */
.rep-card {
    background: #ffffff;
    border: 1.5px solid #e2e8f0;
    border-radius: 8px;
    display: flex;
    gap: 10px;
    align-items: flex-start;
    box-shadow: 0 1px 3px rgba(0,0,0,0.02);
}
.rep-card.border-accent {
    border-left: 4px solid #3b82f6;
}
.rep-num {
    background: #e2e8f0;
    color: #1e293b;
    font-weight: 800;
    border-radius: 6px;
    flex-shrink: 0;
    display: flex;
    align-items: center;
    justify-content: center;
}
.rep-text {
    color: #1e293b;
    font-weight: 500;
}

/* Footer note */
.page-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-top: 1px solid #f1f5f9;
    padding-top: 6px;
    margin-top: 8px;
    font-size: 11px;
    color: #94a3b8;
    flex-shrink: 0;
}

/* COVER PAGE SPECIFICS */
.cover-page {
    justify-content: center;
    align-items: center;
    text-align: center;
    background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
    color: #ffffff;
    padding: 25mm;
}
.cover-inner {
    border: 2px solid rgba(217, 119, 6, 0.4);
    border-radius: 16px;
    padding: 30px 45px;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background: rgba(15, 23, 42, 0.6);
    box-shadow: 0 20px 40px rgba(0,0,0,0.5);
}
.cover-tag {
    font-size: 14px;
    font-weight: 800;
    letter-spacing: 3px;
    text-transform: uppercase;
    color: #f59e0b;
    background: rgba(245, 158, 11, 0.12);
    border: 1px solid rgba(245, 158, 11, 0.3);
    padding: 6px 18px;
    border-radius: 30px;
    margin-bottom: 20px;
}
.cover-title {
    font-size: 44px;
    font-weight: 900;
    letter-spacing: 1px;
    line-height: 1.1;
    margin-bottom: 12px;
    color: #ffffff;
}
.cover-subtitle {
    font-size: 26px;
    font-weight: 600;
    color: #cbd5e1;
    margin-bottom: 28px;
}
.cover-subtitle span {
    color: #f59e0b;
}
.cover-pills {
    display: flex;
    gap: 15px;
    margin-bottom: 25px;
}
.cover-pill {
    background: rgba(255, 255, 255, 0.08);
    border: 1px solid rgba(255, 255, 255, 0.15);
    padding: 8px 18px;
    border-radius: 20px;
    font-size: 13px;
    font-weight: 600;
    color: #e2e8f0;
}
.cover-desc {
    font-size: 14px;
    color: #94a3b8;
    max-width: 680px;
    line-height: 1.5;
}

/* INDEX PAGE SPECIFICS */
.index-grid {
    flex: 1;
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-gap: 8px 16px;
    margin-bottom: 12px;
}
.index-item {
    font-size: 12.5px;
    font-weight: 600;
    color: #1e293b;
    display: flex;
    align-items: center;
    gap: 8px;
    background: #f8fafc;
    border: 1px solid #e2e8f0;
    border-radius: 6px;
    padding: 6px 10px;
}
.index-item-num {
    background: #0f172a;
    color: #ffffff;
    font-size: 11px;
    font-weight: 700;
    padding: 2px 7px;
    border-radius: 4px;
    flex-shrink: 0;
}
.index-item-text {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
.advice-card {
    background: #fffbeb;
    border: 1px solid #fef3c7;
    border-left: 5px solid #d97706;
    border-radius: 6px;
    padding: 10px 16px;
    font-size: 13px;
    color: #92400e;
    font-weight: 500;
    line-height: 1.4;
    flex-shrink: 0;
}

/* BALAS DE REPUESTO PAGE */
.balas-grid {
    flex: 1;
    display: grid;
    grid-template-columns: 1fr 1fr;
    grid-gap: 12px 16px;
    min-height: 0;
}
.bala-card {
    background: #f8fafc;
    border: 1.5px solid #e2e8f0;
    border-left: 4px solid #ef4444; /* red accent for rapid fire */
    border-radius: 8px;
    padding: 12px 14px;
    display: flex;
    gap: 10px;
    align-items: center;
}
.bala-num {
    background: #fee2e2;
    color: #b91c1c;
    font-weight: 800;
    font-size: 13px;
    width: 26px;
    height: 26px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
}
.bala-text {
    font-size: 14.5px;
    font-weight: 600;
    color: #0f172a;
    line-height: 1.35;
}
"""

def render_page(p):
    ptype = p['type']
    
    if ptype == 'cover':
        return f"""
        <div class="page cover-page">
            <div class="cover-inner">
                <div class="cover-tag">Guión Técnico de Grabación</div>
                <h1 class="cover-title">CONVERSACIONES EN OBRADOR</h1>
                <div class="cover-subtitle">Gustavo Mira <span>&amp;</span> Ernesto Mira</div>
                <div class="cover-pills">
                    <div class="cover-pill">🎙️ Formato Horizontal para Mesa</div>
                    <div class="cover-pill">⏱️ 22 Bloques Temáticos</div>
                    <div class="cover-pill">🎯 Pregunta Principal + Repreguntas</div>
                </div>
                <div class="cover-desc">
                    {escape_html(p['version'])}<br>
                    <strong>{escape_html(p['note'])}</strong>
                </div>
            </div>
        </div>
        """
        
    elif ptype == 'index':
        items_html = []
        for it in p['items']:
            parts = it.split('.', 1)
            num = parts[0].strip() if len(parts) > 1 else ''
            txt = parts[1].strip() if len(parts) > 1 else it
            items_html.append(f"""
            <div class="index-item">
                <span class="index-item-num">{num}</span>
                <span class="index-item-text">{escape_html(txt)}</span>
            </div>
            """)
            
        return f"""
        <div class="page">
            <div class="top-header">
                <div class="show-title">Conversaciones en Obrador</div>
                <div class="show-guests">Gustavo Mira y Ernesto Mira</div>
                <div class="page-badge">PÁGINA 2 · MAPA DEL GUIÓN</div>
            </div>
            <div class="block-header">
                <h2 class="block-title" style="font-size: 26px;">🗺️ Mapa Del Guión de la Entrevista</h2>
            </div>
            <div class="index-grid">
                {''.join(items_html)}
            </div>
            <div class="advice-card">
                <strong>💡 Consejo de uso en mesa:</strong> {escape_html(p['advice'])}
            </div>
            <div class="page-footer">
                <div>Conversaciones en Obrador · Raúl Asencio Pastelerías</div>
                <div>Estructura general de temas para podcast</div>
            </div>
        </div>
        """
        
    elif ptype == 'backup_bullets':
        bullets_html = []
        for idx, b in enumerate(p['bullets']):
            bullets_html.append(f"""
            <div class="bala-card">
                <div class="bala-num">{idx + 1}</div>
                <div class="bala-text">{escape_html(b)}</div>
            </div>
            """)
            
        return f"""
        <div class="page">
            <div class="top-header">
                <div class="show-title">Conversaciones en Obrador</div>
                <div class="show-guests">Gustavo Mira y Ernesto Mira</div>
                <div class="page-badge">PÁGINA 25 · RECURSOS</div>
            </div>
            <div class="block-header" style="margin-bottom: 8px;">
                <h2 class="block-title" style="font-size: 26px; color: #b91c1c;">⚡ {escape_html(p['title'])}</h2>
                <div style="font-size: 13.5px; color: #475569; margin-top: 4px; font-weight: 500;">
                    {escape_html(p['intro'])}
                </div>
            </div>
            <div class="balas-grid">
                {''.join(bullets_html)}
            </div>
            <div class="page-footer">
                <div>Conversaciones en Obrador · Balas de repuesto y dinamización</div>
                <div>Pág. 25 de 25</div>
            </div>
        </div>
        """
        
    elif ptype == 'block':
        # Calculate dynamic sizes based on questions and characters
        main_len = len(p['main_full'])
        repregs = p['repreguntas']
        rep_count = len(repregs)
        tot_rep_len = sum(len(r['full_text']) for r in repregs)
        total_len = main_len + tot_rep_len
        
        # Grid columns for repreguntas
        # If 1 repregunta: 1 column
        # If 2 repreguntas: 2 columns
        # If >= 3: 2 columns
        grid_cols = 1 if rep_count == 1 else 2
        
        # Sizing categories:
        # LOW DENSITY: total_len < 400 and rep_count <= 2
        # MEDIUM-HIGH: rep_count >= 5 or total_len > 750
        # MEDIUM: all others
        if rep_count <= 1:
            # Huge, generous card
            title_size = "26px"
            main_card_padding = "18px 22px"
            main_q_size = "22px"
            main_q_lh = "1.42"
            main_num_size = "24px"
            main_num_w = "42px"
            main_num_h = "42px"
            
            rep_card_padding = "20px 24px"
            rep_size = "20px"
            rep_lh = "1.45"
            rep_num_size = "22px"
            rep_num_w = "38px"
            rep_num_h = "38px"
            gap = "14px"
            
        elif rep_count == 2:
            title_size = "25px"
            main_card_padding = "16px 20px"
            main_q_size = "20px"
            main_q_lh = "1.4"
            main_num_size = "22px"
            main_num_w = "38px"
            main_num_h = "38px"
            
            rep_card_padding = "16px 20px"
            rep_size = "18px"
            rep_lh = "1.4"
            rep_num_size = "19px"
            rep_num_w = "34px"
            rep_num_h = "34px"
            gap = "12px"
            
        elif rep_count == 3:
            title_size = "24px"
            main_card_padding = "14px 18px"
            main_q_size = "18.5px"
            main_q_lh = "1.38"
            main_num_size = "20px"
            main_num_w = "34px"
            main_num_h = "34px"
            
            rep_card_padding = "13px 16px"
            rep_size = "16.5px"
            rep_lh = "1.38"
            rep_num_size = "17px"
            rep_num_w = "30px"
            rep_num_h = "30px"
            gap = "10px"
            
        elif rep_count == 4:
            # 2x2 grid
            title_size = "23px"
            main_card_padding = "12px 16px"
            main_q_size = "17.5px"
            main_q_lh = "1.35"
            main_num_size = "19px"
            main_num_w = "32px"
            main_num_h = "32px"
            
            rep_card_padding = "11px 14px"
            rep_size = "15px"
            rep_lh = "1.35"
            rep_num_size = "16px"
            rep_num_w = "28px"
            rep_num_h = "28px"
            gap = "9px"
            
        elif rep_count == 5:
            # 5 items in 2 columns
            title_size = "22px"
            main_card_padding = "11px 15px"
            main_q_size = "16.5px"
            main_q_lh = "1.32"
            main_num_size = "18px"
            main_num_w = "30px"
            main_num_h = "30px"
            
            rep_card_padding = "9px 12px"
            rep_size = "14px"
            rep_lh = "1.32"
            rep_num_size = "15px"
            rep_num_w = "26px"
            rep_num_h = "26px"
            gap = "7px"
            
        else: # rep_count >= 6 (P13 has 6 repreguntas)
            title_size = "21px"
            main_card_padding = "10px 14px"
            main_q_size = "16px"
            main_q_lh = "1.3"
            main_num_size = "17px"
            main_num_w = "28px"
            main_num_h = "28px"
            
            rep_card_padding = "8px 11px"
            rep_size = "13.5px"
            rep_lh = "1.3"
            rep_num_size = "14px"
            rep_num_w = "24px"
            rep_num_h = "24px"
            gap = "6px"

        repregs_html = []
        for r in repregs:
            tag_display = ""
            if r['tag'] == 'ULTIMA':
                tag_display = '<span style="background:#ef4444; color:#fff; font-size:10px; font-weight:800; padding:2px 6px; border-radius:3px; margin-right:6px;">ÚLTIMA PREGUNTA</span>'
                
            num_display = f'<div class="rep-num" style="width:{rep_num_w}; height:{rep_num_h}; font-size:{rep_num_size};">{r["num"]}</div>' if r['num'] else ''
            
            repregs_html.append(f"""
            <div class="rep-card" style="padding: {rep_card_padding};">
                {num_display}
                <div class="rep-text" style="font-size: {rep_size}; line-height: {rep_lh};">
                    {tag_display}{escape_html(r['body'])}
                </div>
            </div>
            """)
            
        block_idx = p['block_index']
        page_num = p['page']
        
        return f"""
        <div class="page">
            <div class="top-header">
                <div class="show-title">Conversaciones en Obrador</div>
                <div class="show-guests">Gustavo Mira y Ernesto Mira</div>
                <div class="page-badge">BLOQUE {block_idx:02d} / 22 · PÁG. {page_num}</div>
            </div>
            
            <div class="block-header">
                <h2 class="block-title" style="font-size: {title_size};">
                    {escape_html(p['title'])}
                </h2>
            </div>
            
            <div class="content-area">
                <!-- Main Question Card -->
                <div class="main-card" style="padding: {main_card_padding};">
                    <div class="main-card-header">
                        <span class="main-badge">Pregunta Principal</span>
                        <span style="font-size: 11px; color: #64748b; font-weight: 600;">Apertura de bloque</span>
                    </div>
                    <div class="main-card-body">
                        <div class="main-q-num" style="width: {main_num_w}; height: {main_num_h}; font-size: {main_num_size};">
                            {p['main_num']}
                        </div>
                        <div class="main-q-text" style="font-size: {main_q_size}; line-height: {main_q_lh};">
                            {escape_html(p['main_body'])}
                        </div>
                    </div>
                </div>
                
                <!-- Repreguntas Grid -->
                <div class="repreguntas-section">
                    <div class="repreguntas-label">
                        <span>Repreguntas / Líneas de Apoyo ({rep_count})</span>
                    </div>
                    <div class="repreguntas-grid" style="grid-template-columns: repeat({grid_cols}, 1fr); gap: {gap};">
                        {''.join(repregs_html)}
                    </div>
                </div>
            </div>
            
            <div class="page-footer">
                <div>Conversaciones en Obrador · Guión de Entrevista en Mesa</div>
                <div>Bloque {block_idx} de 22</div>
            </div>
        </div>
        """

pages_html_list = [render_page(p) for p in pages_data]

full_html = f"""<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Guión Podcast - Gustavo Mira y Ernesto Mira (Horizontal)</title>
<style>
{css}
</style>
</head>
<body>
{''.join(pages_html_list)}
</body>
</html>
"""

html_path = r'c:\fuentes\proyectos delphi\RAUL_ASENCIO\GESTION\scratch\podcast_script_horizontal.html'
pdf_path = r'c:\fuentes\proyectos delphi\RAUL_ASENCIO\GESTION\documentacion raul asencio\guion_podcast_gustavo_ernesto_horizontal.pdf'

with open(html_path, 'w', encoding='utf-8') as f:
    f.write(full_html)

print("Generated HTML successfully.")

# Convert to PDF via Chrome
cmd = [
    r'C:\Program Files\Google\Chrome\Application\chrome.exe',
    '--headless=new',
    '--disable-gpu',
    '--no-pdf-header-footer',
    f'--print-to-pdf={pdf_path}',
    html_path
]

res = subprocess.run(cmd, capture_output=True, text=True)
print("Chrome execution return code:", res.returncode)

# Verify with PyMuPDF
doc = fitz.open(pdf_path)
print(f"Generated PDF has {len(doc)} pages.")
for i in range(len(doc)):
    p = doc[i]
    print(f"Page {i+1}: {p.rect.width:.1f} x {p.rect.height:.1f} pt")
