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;')

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: #ffffff;
    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: 11mm 16mm 10mm 16mm;
    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: 6px;
    margin-bottom: 8px;
    flex-shrink: 0;
}
.show-title {
    font-size: 13.5px;
    font-weight: 800;
    text-transform: uppercase;
    letter-spacing: 1.5px;
    color: #b45309;
    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: 13px;
    color: #475569;
    font-weight: 600;
}
.page-badge {
    background: #0f172a;
    color: #ffffff;
    font-size: 12.5px;
    font-weight: 800;
    padding: 3px 14px;
    border-radius: 20px;
    letter-spacing: 0.8px;
}

/* Block Title */
.block-header {
    margin-bottom: 10px;
    flex-shrink: 0;
}
.block-title {
    font-weight: 900;
    color: #0f172a;
    line-height: 1.15;
    letter-spacing: -0.4px;
}

/* Content Area fills remaining height */
.content-area {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: 0;
    gap: 10px;
}

/* Main Question Card */
.main-card {
    background: #f8fafc;
    border: 2px solid #cbd5e1;
    border-left: 8px solid #d97706;
    border-radius: 10px;
    box-shadow: 0 2px 5px rgba(0,0,0,0.03);
    display: flex;
    flex-direction: column;
    justify-content: center;
    flex-shrink: 0;
}
.main-card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-bottom: 5px;
    margin-bottom: 6px;
    border-bottom: 1px dashed #cbd5e1;
    flex-shrink: 0;
}
.main-badge {
    background: #d97706;
    color: #ffffff;
    font-size: 11.5px;
    font-weight: 800;
    text-transform: uppercase;
    letter-spacing: 1.2px;
    padding: 2px 8px;
    border-radius: 4px;
}
.main-card-body {
    display: flex;
    gap: 14px;
    align-items: center;
    flex: 1;
}
.main-q-num {
    background: #0f172a;
    color: #ffffff;
    font-weight: 900;
    border-radius: 8px;
    flex-shrink: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 2px 4px rgba(0,0,0,0.15);
}
.main-q-text {
    font-weight: 750;
    color: #0f172a;
    flex: 1;
}

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

/* Individual Repregunta Card */
.rep-card {
    background: #ffffff;
    border: 1.5px solid #cbd5e1;
    border-left: 4px solid #3b82f6;
    border-radius: 8px;
    display: flex;
    gap: 12px;
    align-items: center;
    box-shadow: 0 1px 3px rgba(0,0,0,0.03);
    min-height: 0;
}
.rep-num {
    background: #e0f2fe;
    color: #0369a1;
    font-weight: 800;
    border-radius: 6px;
    flex-shrink: 0;
    display: flex;
    align-items: center;
    justify-content: center;
}
.rep-text {
    color: #1e293b;
    font-weight: 600;
    flex: 1;
}

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

/* COVER PAGE */
.cover-page {
    justify-content: center;
    align-items: center;
    text-align: center;
    background: radial-gradient(circle at center, #1e293b 0%, #0f172a 100%);
    color: #ffffff;
    padding: 20mm;
}
.cover-inner {
    border: 2px solid rgba(217, 119, 6, 0.45);
    border-radius: 20px;
    padding: 35px 50px;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background: rgba(15, 23, 42, 0.65);
    box-shadow: 0 25px 50px rgba(0,0,0,0.6);
}
.cover-tag {
    font-size: 14px;
    font-weight: 800;
    letter-spacing: 3.5px;
    text-transform: uppercase;
    color: #f59e0b;
    background: rgba(245, 158, 11, 0.15);
    border: 1px solid rgba(245, 158, 11, 0.35);
    padding: 7px 22px;
    border-radius: 30px;
    margin-bottom: 22px;
}
.cover-title {
    font-size: 46px;
    font-weight: 900;
    letter-spacing: 1.5px;
    line-height: 1.1;
    margin-bottom: 14px;
    color: #ffffff;
}
.cover-subtitle {
    font-size: 28px;
    font-weight: 600;
    color: #cbd5e1;
    margin-bottom: 28px;
}
.cover-subtitle span {
    color: #f59e0b;
}
.cover-pills {
    display: flex;
    gap: 16px;
    margin-bottom: 26px;
}
.cover-pill {
    background: rgba(255, 255, 255, 0.08);
    border: 1px solid rgba(255, 255, 255, 0.18);
    padding: 9px 20px;
    border-radius: 25px;
    font-size: 14px;
    font-weight: 600;
    color: #f1f5f9;
}
.cover-desc {
    font-size: 15px;
    color: #94a3b8;
    max-width: 700px;
    line-height: 1.55;
}

/* INDEX PAGE */
.index-grid {
    flex: 1;
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-gap: 8px 14px;
    margin-bottom: 10px;
}
.index-item {
    font-size: 13.5px;
    font-weight: 650;
    color: #0f172a;
    display: flex;
    align-items: center;
    gap: 9px;
    background: #f8fafc;
    border: 1.5px solid #e2e8f0;
    border-radius: 6px;
    padding: 7px 10px;
}
.index-item-num {
    background: #0f172a;
    color: #ffffff;
    font-size: 11.5px;
    font-weight: 800;
    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: 1.5px solid #fef3c7;
    border-left: 6px solid #d97706;
    border-radius: 8px;
    padding: 12px 18px;
    font-size: 14px;
    color: #92400e;
    font-weight: 600;
    line-height: 1.45;
    flex-shrink: 0;
}

/* BALAS DE REPUESTO */
.balas-grid {
    flex: 1;
    display: grid;
    grid-template-columns: 1fr 1fr;
    grid-gap: 10px 16px;
    min-height: 0;
}
.bala-card {
    background: #f8fafc;
    border: 1.5px solid #cbd5e1;
    border-left: 5px solid #ef4444;
    border-radius: 8px;
    padding: 10px 14px;
    display: flex;
    gap: 12px;
    align-items: center;
    box-shadow: 0 1px 3px rgba(0,0,0,0.03);
}
.bala-num {
    background: #fee2e2;
    color: #b91c1c;
    font-weight: 900;
    font-size: 15px;
    width: 32px;
    height: 32px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
}
.bala-text {
    font-size: 17px;
    font-weight: 700;
    color: #0f172a;
    line-height: 1.35;
}
"""

def render_page_v2(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">🎯 Letra Grande para Fácil Lectura</div>
                </div>
                <div class="cover-desc">
                    {escape_html(p['version'])}<br><br>
                    <strong style="color:#f8fafc;">{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: 27px; color: #b91c1c;">⚡ {escape_html(p['title'])}</h2>
                <div style="font-size: 14px; color: #475569; margin-top: 3px; font-weight: 600;">
                    {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':
        repregs = p['repreguntas']
        rep_count = len(repregs)
        
        # Determine layout and typography parameters based on repreguntas count and length
        # We want BIG, ROOM-FILLING typography!
        if rep_count == 1:
            # 1 repregunta (P8, P24): 2 massive cards sharing height
            title_size = "28px"
            main_card_flex = "1"
            main_card_padding = "20px 26px"
            main_q_size = "28px"
            main_q_lh = "1.45"
            main_num_size = "28px"
            main_num_w = "52px"
            main_num_h = "52px"
            
            repregs_grid_css = "grid-template-columns: 1fr; gap: 0px;"
            rep_card_css = "flex: 1; padding: 22px 28px;"
            rep_size = "26px"
            rep_lh = "1.45"
            rep_num_size = "26px"
            rep_num_w = "48px"
            rep_num_h = "48px"
            
        elif rep_count == 2:
            # 2 repreguntas (P4, P12, P20, P23): 2 columns side by side
            title_size = "26px"
            main_card_flex = "0 0 auto"
            main_card_padding = "18px 24px"
            main_q_size = "23px"
            main_q_lh = "1.42"
            main_num_size = "24px"
            main_num_w = "46px"
            main_num_h = "46px"
            
            repregs_grid_css = "grid-template-columns: 1fr 1fr; gap: 14px;"
            rep_card_css = "padding: 20px 22px;"
            rep_size = "21px"
            rep_lh = "1.42"
            rep_num_size = "22px"
            rep_num_w = "42px"
            rep_num_h = "42px"
            
        elif rep_count == 3:
            # 3 repreguntas: 2 on top row, 1 spanning bottom row full width
            title_size = "25px"
            main_card_flex = "0 0 auto"
            main_card_padding = "16px 20px"
            main_q_size = "21px"
            main_q_lh = "1.4"
            main_num_size = "22px"
            main_num_w = "42px"
            main_num_h = "42px"
            
            repregs_grid_css = "grid-template-columns: 1fr 1fr; grid-template-rows: 1fr 1fr; gap: 11px;"
            rep_card_css = "padding: 14px 18px;"
            rep_size = "18.5px"
            rep_lh = "1.38"
            rep_num_size = "19px"
            rep_num_w = "36px"
            rep_num_h = "36px"
            
        elif rep_count == 4:
            # 4 repreguntas: 2x2 grid
            title_size = "24px"
            main_card_flex = "0 0 auto"
            main_card_padding = "14px 18px"
            main_q_size = "19.5px"
            main_q_lh = "1.38"
            main_num_size = "20px"
            main_num_w = "38px"
            main_num_h = "38px"
            
            repregs_grid_css = "grid-template-columns: 1fr 1fr; grid-template-rows: 1fr 1fr; gap: 10px;"
            rep_card_css = "padding: 12px 16px;"
            rep_size = "17.5px"
            rep_lh = "1.36"
            rep_num_size = "17.5px"
            rep_num_w = "32px"
            rep_num_h = "32px"
            
        elif rep_count == 5:
            # 5 repreguntas: 2 cols, 3 rows, 5th spans full width
            title_size = "23px"
            main_card_flex = "0 0 auto"
            main_card_padding = "12px 16px"
            main_q_size = "18.5px"
            main_q_lh = "1.34"
            main_num_size = "19px"
            main_num_w = "34px"
            main_num_h = "34px"
            
            repregs_grid_css = "grid-template-columns: 1fr 1fr; grid-template-rows: 1fr 1fr 1fr; gap: 8px;"
            rep_card_css = "padding: 10px 14px;"
            rep_size = "16px"
            rep_lh = "1.33"
            rep_num_size = "16px"
            rep_num_w = "28px"
            rep_num_h = "28px"
            
        else: # rep_count >= 6 (P13 has 6 repreguntas)
            title_size = "22px"
            main_card_flex = "0 0 auto"
            main_card_padding = "11px 15px"
            main_q_size = "18px"
            main_q_lh = "1.32"
            main_num_size = "18px"
            main_num_w = "32px"
            main_num_h = "32px"
            
            repregs_grid_css = "grid-template-columns: 1fr 1fr; grid-template-rows: 1fr 1fr 1fr; gap: 7px;"
            rep_card_css = "padding: 9px 13px;"
            rep_size = "16px"
            rep_lh = "1.32"
            rep_num_size = "15.5px"
            rep_num_w = "26px"
            rep_num_h = "26px"

        repregs_html = []
        for idx, r in enumerate(repregs):
            tag_display = ""
            if r['tag'] == 'ULTIMA':
                tag_display = '<span style="background:#ef4444; color:#fff; font-size:12px; font-weight:800; padding:3px 8px; border-radius:4px; margin-right:8px; vertical-align:middle;">Ú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 ''
            
            # If 3 repreguntas and this is the 3rd one: span 2 columns
            span_style = ""
            if rep_count == 3 and idx == 2:
                span_style = "grid-column: 1 / -1;"
            elif rep_count == 5 and idx == 4:
                span_style = "grid-column: 1 / -1;"
                
            repregs_html.append(f"""
            <div class="rep-card" style="{rep_card_css} {span_style}">
                {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="flex: {main_card_flex}; padding: {main_card_padding};">
                    <div class="main-card-header">
                        <span class="main-badge">Pregunta Principal</span>
                        <span style="font-size: 12px; color: #64748b; font-weight: 700;">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="{repregs_grid_css}">
                        {''.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_v2(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_v2.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 v2 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.")

# Render new previews
out_dir = r'c:\fuentes\proyectos delphi\RAUL_ASENCIO\GESTION\scratch\previews_v2'
os.makedirs(out_dir, exist_ok=True)
test_pages = [1, 2, 3, 5, 7, 8, 13, 24, 25]

for pno in test_pages:
    page = doc[pno - 1]
    pix = page.get_pixmap(dpi=150)
    img_path = os.path.join(out_dir, f'page_{pno:02d}.png')
    pix.save(img_path)

print("All previews_v2 saved.")
