from fpdf import FPDF
import io
import os
from datetime import datetime

def generate_evaluation_pdf(data, colaborador_name, colaborador_cedula, periodo_desc, evaluador_name, ano_desc, id_trimestre, city_name=""):
    """
    Generates a PDF buffer for an evaluation report based on the 2026 format.
    """
    # Determine dates based on id_trimestre
    desde_date = ""
    hasta_date = ""
    if id_trimestre == 1:
        desde_date = f"01/01/{ano_desc}"
        hasta_date = f"31/03/{ano_desc}"
    elif id_trimestre == 2:
        desde_date = f"01/04/{ano_desc}"
        hasta_date = f"30/06/{ano_desc}"
    elif id_trimestre == 3:
        desde_date = f"01/07/{ano_desc}"
        hasta_date = f"30/09/{ano_desc}"
    elif id_trimestre == 4:
        desde_date = f"01/10/{ano_desc}"
        hasta_date = f"31/12/{ano_desc}"

    # Create PDF
    pdf = FPDF()
    pdf.add_page()
    pdf.set_auto_page_break(auto=True, margin=15)
    
    # Logo
    logo_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static', 'img', 'logo.png')
    if os.path.exists(logo_path):
        pdf.image(logo_path, 10, 8, 35)
    
    # Title
    pdf.set_font("Helvetica", "B", 14)
    pdf.set_y(25)
    pdf.cell(w=0, h=8, txt="NOTIFICACIÓN DE RESULTADOS", ln=1, align="C")
    pdf.cell(w=0, h=8, txt=f"EVALUACIÓN DEL DESEMPEÑO AÑO {ano_desc}", ln=1, align="C")
    pdf.ln(15)

    # Main Table
    pdf.set_font("Helvetica", "", 10)
    
    # Row 1
    pdf.cell(w=110, h=10, txt="Por medio de la presente, se notifica al trabajador (a)", border=1, align="L")
    pdf.set_font("Helvetica", "B", 10)
    pdf.cell(w=80, h=10, txt=str(colaborador_name), border=1, align="C", ln=1)
    
    # Row 2
    pdf.set_font("Helvetica", "", 10)
    pdf.cell(w=75, h=10, txt="Titular de la Cédula de Identidad Número:", border=1, align="L")
    pdf.set_font("Helvetica", "B", 10)
    pdf.cell(w=45, h=10, txt=str(colaborador_cedula), border=1, align="C")
    pdf.set_font("Helvetica", "", 10)
    pdf.cell(w=20, h=10, txt="Cargo:", border=1, align="C")
    pdf.cell(w=50, h=10, txt="", border=1, align="C", ln=1)

    # Shorten the Escala description
    remark = str(data.get('escala_remark', ''))
    short_remark = remark
    remark_lower = remark.lower()
    if remark_lower.startswith("no cumpli") or "deficiente" in remark_lower:
        short_remark = "No cumplió"
    elif "ordinario" in remark_lower or "esperado" in remark_lower:
        short_remark = "Cumplimiento Ordinario"
    elif "muy bueno" in remark_lower:
        short_remark = "Muy Bueno"
    elif "bueno" in remark_lower:
        short_remark = "Bueno"
    elif "excelente" in remark_lower or "excepcional" in remark_lower:
        short_remark = "Excelente"

    font_size = 10
    if len(short_remark) > 15:
        font_size = 8

    # Row 3
    pdf.set_font("Helvetica", "", 10)
    pdf.cell(w=110, h=10, txt="Que su desempeño ha sido calificado con el Rango de actuación:", border=1, align="L")
    pdf.set_font("Helvetica", "B", font_size)
    pdf.cell(w=40, h=10, txt=short_remark, border=1, align="C")
    pdf.set_font("Helvetica", "B", 10)
    pdf.cell(w=40, h=10, txt=str(periodo_desc), border=1, align="C", ln=1)

    # Row 4
    pdf.set_font("Helvetica", "", 10)
    pdf.cell(w=110, h=10, txt="De acuerdo a la puntuación obtenida, la cual fue de:", border=1, align="L")
    pdf.set_font("Helvetica", "B", 10)
    pdf.cell(w=80, h=10, txt=str(round(data['total_evaluacion_score'], 2)), border=1, align="C", ln=1)

    # Row 5
    pdf.set_font("Helvetica", "", 9)
    pdf.cell(w=75, h=10, txt="Correspondiente al trimestre de evaluación:", border=1, align="C")
    pdf.set_font("Helvetica", "B", 9)
    pdf.cell(w=55, h=10, txt=f"Desde: {desde_date}", border=1, align="C")
    pdf.cell(w=60, h=10, txt=f"Hasta: {hasta_date}", border=1, align="C", ln=1)

    # Row 6
    pdf.set_font("Helvetica", "B", 9)
    pdf.cell(w=150, h=10, txt="PRESENTÓ CERTIFICADO DE CURSO DE LA ESCUELA DE PLANIFICACIÓN", border=1, align="C")
    pdf.set_font("Helvetica", "", 10)
    pdf.cell(w=40, h=10, txt="SÍ" if data.get('has_course') else "NO", border=1, align="C", ln=1)

    pdf.ln(10)

    # Document expide
    current_date_str = datetime.now().strftime('%d/%m/%Y')
    pdf.set_font("Helvetica", "", 10)
    city_text = f" {city_name}" if city_name else " _________________"
    pdf.cell(w=0, h=10, txt=f"Documento que se expide en la ciudad de{city_text} en fecha {current_date_str}", ln=1, align="L")
    pdf.ln(10)

    # Signatures - Section 1
    pdf.set_font("Helvetica", "B", 9)
    pdf.cell(w=0, h=8, txt="PARA SER LLENADO POR GERENCIA GENERAL DE TALENTO HUMANO / JEFE DE DIVISIÓN DE TALENTO HUMANO", ln=1, align="C")
    pdf.ln(5)
    
    pdf.set_font("Helvetica", "B", 9)
    # Col 1
    pdf.cell(w=95, h=8, txt="NOMBRE/APELLIDO:___________________________________", align="L")
    pdf.cell(w=95, h=8, txt="NOMBRE/APELLIDO:___________________________________", align="L", ln=1)
    pdf.cell(w=95, h=8, txt="CÉDULA ____________________________________________", align="L")
    pdf.cell(w=95, h=8, txt="CÉDULA ____________________________________________", align="L", ln=1)
    pdf.cell(w=95, h=8, txt="FIRMA _____________________________________________", align="L")
    pdf.cell(w=95, h=8, txt="FIRMA _____________________________________________", align="L", ln=1)
    
    pdf.ln(10)

    # Signatures - Section 2
    pdf.set_font("Helvetica", "B", 9)
    pdf.cell(w=0, h=8, txt="PARA SER LLENADO POR EL SUPERVISOR INMEDIATO Y EL TRABAJADOR", ln=1, align="C")
    pdf.ln(5)

    pdf.cell(w=95, h=8, txt="Firma del Evaluado: ___________________________________", align="C")
    pdf.cell(w=95, h=8, txt="Firma del Evaluador: __________________________________", align="C", ln=1)
    pdf.cell(w=95, h=8, txt="Fecha: ______________________________________________", align="C")
    pdf.cell(w=95, h=8, txt="Fecha: ______________________________________________", align="C", ln=1)

    pdf.ln(15)

    # Note
    note_text = "NOTA: En caso que el trabajador (a) presente inconformidad con el resultado de su evaluación, podrá presentar su reclamo por escrito a la Gerencia General de Gestión de Talento Humano, en un lapso de cinco (5) días hábiles siguientes a partir de la fecha que fue notificado del resultado de la evaluación."
    pdf.set_font("Helvetica", "B", 8)
    pdf.multi_cell(w=0, h=5, txt=note_text, border=1, align="C")

    # Output
    buffer = io.BytesIO()
    pdf.output(buffer)
    buffer.seek(0)
    
    return buffer
