#!/usr/bin/env python3
"""Genera vedabase_archive.pdf desde los volcados de D1 en /tmp/pdfdata/.
Incluye: título de libro, título de capítulo (derivado del ref), traducción (negrita),
purport. EXCLUYE verso/transliteración/devanagari/bengalí/sinónimos.
Formato: 8pt, interlineado 1, márgenes 1.5cm, sin líneas en blanco. DejaVu Serif (IAST)."""
import json, re, glob, os, unicodedata
from fpdf import FPDF

MPL='/opt/homebrew/lib/python3.14/site-packages/matplotlib/mpl-data/fonts/ttf'
DATA='/tmp/pdfdata'
OUT='vedabase_archive.pdf'

BOOK_TITLES={
 'bg':'Bhagavad-gītā As It Is','iso':'Śrī Īśopaniṣad','sb':'Śrīmad-Bhāgavatam',
 'cc':'Śrī Caitanya-caritāmṛta','kb':'Kṛṣṇa, the Supreme Personality of Godhead',
 'nod':'The Nectar of Devotion','tlc':'Teachings of Lord Caitanya','noi':'The Nectar of Instruction',
 'ssr':'The Science of Self-Realization','tqk':'Teachings of Queen Kuntī','pop':'The Path of Perfection',
 'rv':'Rāja-vidyā: The King of Knowledge','pqpa':'Perfect Questions, Perfect Answers',
 'ttp':'Transcendental Teachings of Prahlāda Mahārāja','ekc':'Elevation to Kṛṣṇa Consciousness',
 'ej':'Easy Journey to Other Planets','lob':'The Light of the Bhāgavata','owk':'On the Way to Kṛṣṇa',
 'poy':'The Perfection of Yoga','bbd':'Beyond Birth and Death','krp':'Kṛṣṇa the Reservoir of Pleasure',
 'lcfl':'Life Comes from Life'}
LILA={'adi':'Ādi-līlā','madhya':'Madhya-līlā','antya':'Antya-līlā'}
ROMAN={1:'One',2:'Two',3:'Three',4:'Four',5:'Five',6:'Six',7:'Seven',8:'Eight',9:'Nine',10:'Ten'}

def clean(t):
    if not t: return ''
    t=t.replace('**','')                       # quitar marcadores de negrita
    t=re.sub(r'\*([^*\n]+)\*', r'\1', t)        # *itálica* -> texto
    t=re.sub(r'^\s*#+\s*', '', t, flags=re.M)   # ## encabezados -> texto
    t=t.replace('((','').replace('))','')       # marcadores de nota
    t=re.sub(r'^\s*>\s*', '', t, flags=re.M)    # blockquote: quitar prefijo
    t=re.sub(r'[ \t]+',' ', t)
    t=re.sub(r'\n\s*\n+', '\n', t)              # SIN líneas en blanco
    return t.strip()

def keep(ref):
    # Excluir lo que NO es de Prabhupāda: SB termina en Canto 10, Cap. 13.
    # Caps. 10.14–10.90 y Cantos 11–12 fueron completados por discípulos.
    p=ref.split('/')
    if p[0]=='sb' and len(p)>=3 and p[1].isdigit() and p[2].isdigit():
        canto,chap=int(p[1]),int(p[2])
        if canto>10 or (canto==10 and chap>=14): return False
    return True

def chapter_label(ref):
    p=ref.split('/'); b=p[0]
    if b=='sb' and len(p)>=3 and p[1].isdigit() and p[2].isdigit():
        return f"Canto {p[1]}, Chapter {p[2]}"
    if b=='cc' and len(p)>=3 and p[2].isdigit():
        return f"{LILA.get(p[1],p[1])}, Chapter {p[2]}"
    if b=='bg' and len(p)>=2 and p[1].isdigit():
        return f"Chapter {p[1]}"
    return None  # libros menores: sin capítulos

class PDF(FPDF):
    def header(self): pass
    def footer(self):
        self.set_y(-10); self.set_font('DJ','',6); self.set_text_color(120)
        self.cell(0,6,str(self.page_no()),align='C'); self.set_text_color(0)

pdf=PDF(orientation='P',unit='mm',format='A4')
pdf.set_margins(15,15,15); pdf.set_auto_page_break(True,12)
pdf.add_font('DJ','',f'{MPL}/DejaVuSerif.ttf')
pdf.add_font('DJ','B',f'{MPL}/DejaVuSerif-Bold.ttf')
pdf.add_font('DJ','I',f'{MPL}/DejaVuSerif-Italic.ttf')
LH=3.2  # interlineado ~1 a 8pt (mm)

files=sorted(glob.glob(f'{DATA}/*.json'))
nverses=0
for fi,f in enumerate(files):
    rows=json.load(open(f))
    rows=rows[0]['results'] if isinstance(rows,dict) else rows
    if not rows: continue
    book=rows[0]['ref'].split('/')[0]
    # --- título de libro (página nueva) ---
    pdf.add_page(); pdf.set_font('DJ','B',16); pdf.set_y(pdf.h/2-20)
    pdf.multi_cell(0,8,BOOK_TITLES.get(book,book),align='C')
    pdf.ln(4); pdf.set_font('DJ','',9)
    pdf.multi_cell(0,5,'A. C. Bhaktivedanta Swami Prabhupāda',align='C')
    pdf.add_page()
    cur_ch=None
    for r in rows:
        ref=r['ref']
        if not keep(ref): continue
        tr=clean(r.get('translation')); pu=clean(r.get('purport'))
        ch=chapter_label(ref)
        if ch and ch!=cur_ch:
            cur_ch=ch
            pdf.set_font('DJ','B',10); pdf.ln(1)
            pdf.multi_cell(0,4,ch);
        vn=ref.split('/')[-1]
        if tr:
            pdf.set_font('DJ','B',8)
            pdf.multi_cell(0,LH,f"{vn}  {tr}",align='J')
        if pu:
            pdf.set_font('DJ','',8)
            pdf.multi_cell(0,LH,pu,align='J')
        nverses+=1
    print(f"  {os.path.basename(f):16} {len(rows):5} versos  → pág {pdf.page_no()}",flush=True)

pdf.output(OUT)
print(f"\n{OUT}: {pdf.page_no()} páginas, {nverses} versos, {os.path.getsize(OUT)//1024//1024} MB")
