from fpdf import FPDF
import os

def generate_pdf(md_file, pdf_file, title):
    print(f"Generando {pdf_file} desde {md_file}...")
    
    if not os.path.exists(md_file):
        print(f"Error: {md_file} no encontrado.")
        return

    pdf = FPDF()
    pdf.add_page()
    
    # Agregar fuente compatible (Arial por defecto, soporta acentos básicos si se usa latin-1)
    # Para soporte completo de UTF-8 en fpdf2 se recomienda cargar una fuente TTF, 
    # pero usaremos la standard con encode/decode para simplicidad y evitar dependencias de archivos de fuente externos.
    
    pdf.set_font("Arial", size=12)
    
    # Leer contenido MD
    with open(md_file, 'r', encoding='utf-8') as f:
        lines = f.readlines()
        
    for line in lines:
        line = line.strip()
        if not line:
            pdf.ln(5)
            continue
            
        # Headers
        if line.startswith("# "):
            pdf.set_font("Arial", "B", 24)
            pdf.set_text_color(26, 60, 38) # Forest Green
            pdf.multi_cell(0, 10, clean_text(line[2:]))
            pdf.set_text_color(0, 0, 0)
            pdf.set_font("Arial", size=12)
            pdf.ln(5)
        elif line.startswith("## "):
            pdf.set_font("Arial", "B", 18)
            pdf.set_text_color(46, 100, 68) # Lighter Green
            pdf.ln(5)
            pdf.multi_cell(0, 10, clean_text(line[3:]))
            pdf.set_text_color(0, 0, 0)
            pdf.set_font("Arial", size=12)
            pdf.ln(2)
        elif line.startswith("### "):
            pdf.set_font("Arial", "B", 14)
            pdf.ln(2)
            pdf.multi_cell(0, 10, clean_text(line[4:]))
            pdf.set_font("Arial", size=12)
        # Lists
        elif line.startswith("- ") or line.startswith("* "):
            pdf.set_x(20)
            pdf.multi_cell(0, 8, chr(149) + " " + clean_text(line[2:]))
        elif line[0].isdigit() and line[1:3] == ". ":
             pdf.set_x(20)
             pdf.multi_cell(0, 8, clean_text(line))
        # Code blocks (simplificado)
        elif line.startswith("```"):
            continue
        # Normal text
        else:
            # Reset X to margin for normal text
            pdf.set_x(10)
            clean = clean_text(line.replace("**", "").replace("`", ""))
            try:
                pdf.multi_cell(0, 8, clean)
            except Exception as e:
                print(f"Warning: Could not print line: {line[:20]}... Error: {e}")


    output_path = os.path.join("web", pdf_file)
    pdf.output(output_path)
    print(f"PDF generado exitosamente: {output_path}")

def clean_text(text):
    """Limpia caracteres markdown y maneja encoding"""
    # Reemplazar caracteres problemáticos para latin-1
    replacements = {
        "á": "a", "é": "e", "í": "i", "ó": "o", "ú": "u",
        "Á": "A", "É": "E", "Í": "I", "Ó": "O", "Ú": "U",
        "ñ": "n", "Ñ": "N", "€": "EUR", "≈": "~",
        "🐛": "", "🔐": "", "💰": "", "📦": "", "✅": "", "🛡️": "", "🌐": "", "🌿": "", "🌱": ""
    }
    for char, rep in replacements.items():
        text = text.replace(char, rep)
    
    try:
        return text.encode('latin-1', 'replace').decode('latin-1')
    except:
        return text

if __name__ == "__main__":
    generate_pdf("GUIDE_ES.md", "GUIA_USUARIO_ES.pdf", "Guía de Usuario Tairuma")
    generate_pdf("GUIDE_EN.md", "USER_GUIDE_EN.pdf", "Tairuma User Guide")
