import os
from reportlab.lib import colors
from reportlab.lib.pagesizes import A4, landscape
from reportlab.lib.units import cm, mm
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.platypus import (
    SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, HRFlowable, Image
)
from reportlab.pdfgen import canvas

class NumberedCanvasLandscape(canvas.Canvas):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._saved_page_states = []

    def showPage(self):
        self._saved_page_states.append(dict(self.__dict__))
        self._startPage()

    def save(self):
        num_pages = len(self._saved_page_states)
        for state in self._saved_page_states:
            self.__dict__.update(state)
            self.draw_header_footer(num_pages)
            super().showPage()
        super().save()

    def draw_header_footer(self, page_count):
        self.saveState()
        self.setFont("Helvetica-Bold", 7.5)
        self.setFillColor(colors.HexColor("#1A365D")) # Navy
        
        # Header
        self.drawString(12*mm, 200*mm, "BRANA / ESTALEIRO ESCOLA EMBRIÃO — MEMORIAL TÉCNICO & MODELO 3D")
        self.setFont("Helvetica", 7.5)
        self.setFillColor(colors.HexColor("#4A5568"))
        self.drawRightString(285*mm, 200*mm, "Saveiro Tradicional 14,80 m — Superfície 3D & Plano de Linhas")
        self.setStrokeColor(colors.HexColor("#CBD5E0"))
        self.setLineWidth(0.5)
        self.line(12*mm, 198*mm, 285*mm, 198*mm)

        # Footer
        self.setStrokeColor(colors.HexColor("#CBD5E0"))
        self.setLineWidth(0.5)
        self.line(12*mm, 9*mm, 285*mm, 9*mm)
        
        self.setFont("Helvetica", 7.5)
        self.setFillColor(colors.HexColor("#718096"))
        self.drawString(12*mm, 5.5*mm, "Professora Assistente: Magdalena (Mada) | Brana Projetos Navais & EEE | Grupo 3")
        page_str = f"Página {self._pageNumber} de {page_count}"
        self.drawRightString(285*mm, 5.5*mm, page_str)
        self.restoreState()

def build_prancha_pdf(output_path):
    doc = SimpleDocTemplate(
        output_path,
        pagesize=landscape(A4),
        leftMargin=12*mm,
        rightMargin=12*mm,
        topMargin=13*mm,
        bottomMargin=11*mm
    )

    styles = getSampleStyleSheet()
    
    primary_color = colors.HexColor("#1A365D")   # Deep Navy
    secondary_color = colors.HexColor("#2B6CB0") # Marine Blue
    dark_neutral = colors.HexColor("#2D3748")    # Charcoal text
    light_bg = colors.HexColor("#F7FAFC")

    title_style = ParagraphStyle(
        'DocTitle',
        parent=styles['Normal'],
        fontName='Helvetica-Bold',
        fontSize=12,
        leading=15,
        textColor=primary_color,
        spaceAfter=1
    )
    
    subtitle_style = ParagraphStyle(
        'DocSubTitle',
        parent=styles['Normal'],
        fontName='Helvetica-Bold',
        fontSize=8,
        leading=10,
        textColor=secondary_color,
        spaceAfter=3
    )

    h1_style = ParagraphStyle(
        'SectionH1',
        parent=styles['Normal'],
        fontName='Helvetica-Bold',
        fontSize=8.5,
        leading=11,
        textColor=primary_color,
        spaceBefore=2,
        spaceAfter=2,
        keepWithNext=True
    )

    body_style = ParagraphStyle(
        'BodyDark',
        parent=styles['Normal'],
        fontName='Helvetica',
        fontSize=7,
        leading=9.5,
        textColor=dark_neutral,
        spaceAfter=1
    )

    table_header_style = ParagraphStyle(
        'TableHeader',
        parent=styles['Normal'],
        fontName='Helvetica-Bold',
        fontSize=6.5,
        leading=8.5,
        textColor=colors.white,
        alignment=1
    )

    table_cell_style = ParagraphStyle(
        'TableCell',
        parent=styles['Normal'],
        fontName='Helvetica',
        fontSize=6.5,
        leading=8.5,
        textColor=dark_neutral,
        alignment=1
    )

    story = []

    # Título
    story.append(Paragraph("MEMORIAL TÉCNICO DE LINHAS E MODELAGEM 3D DO CASCO", subtitle_style))
    story.append(Paragraph("Saveiro Tradicional 14,80 m — Casco Redondo & Tabela de Cotas (Grupo 3)", title_style))
    story.append(HRFlowable(width="100%", thickness=0.8, color=primary_color, spaceBefore=1, spaceAfter=3))

    # Tabela de Cotas
    # Largura total disponível = 273 mm
    cotas_data = [
        [
            Paragraph("Baliza", table_header_style),
            Paragraph("Posição X (mm)", table_header_style),
            Paragraph("Alt. Quilha (mm)", table_header_style),
            Paragraph("Alt. Borda (mm)", table_header_style),
            Paragraph("Meia-Boca 25% (mm)", table_header_style),
            Paragraph("Meia-Boca 50% (mm)", table_header_style),
            Paragraph("Meia-Boca 75% (mm)", table_header_style),
            Paragraph("Meia-Boca Borda (mm)", table_header_style)
        ],
        [Paragraph("1 (Popa)", table_cell_style), Paragraph("0,0", table_cell_style), Paragraph("845,7", table_cell_style), Paragraph("2008,6", table_cell_style), Paragraph("1465,2", table_cell_style), Paragraph("1640,0", table_cell_style), Paragraph("1686,5", table_cell_style), Paragraph("1691,4", table_cell_style)],
        [Paragraph("2", table_cell_style), Paragraph("2467,0", table_cell_style), Paragraph("191,6", table_cell_style), Paragraph("1779,2", table_cell_style), Paragraph("1879,5", table_cell_style), Paragraph("2095,2", table_cell_style), Paragraph("2151,0", table_cell_style), Paragraph("2156,6", table_cell_style)],
        [Paragraph("3", table_cell_style), Paragraph("4933,0", table_cell_style), Paragraph("14,3", table_cell_style), Paragraph("1632,0", table_cell_style), Paragraph("2064,8", table_cell_style), Paragraph("2285,4", table_cell_style), Paragraph("2339,6", table_cell_style), Paragraph("2344,5", table_cell_style)],
        [Paragraph("4 (Mestra)", table_cell_style), Paragraph("7400,0", table_cell_style), Paragraph("0,0", table_cell_style), Paragraph("1585,7", table_cell_style), Paragraph("2171,3", table_cell_style), Paragraph("2394,6", table_cell_style), Paragraph("2447,9", table_cell_style), Paragraph("2452,6", table_cell_style)],
        [Paragraph("5", table_cell_style), Paragraph("9867,0", table_cell_style), Paragraph("90,9", table_cell_style), Paragraph("1696,8", table_cell_style), Paragraph("1917,4", table_cell_style), Paragraph("2161,0", table_cell_style), Paragraph("2228,8", table_cell_style), Paragraph("2236,4", table_cell_style)],
        [Paragraph("6", table_cell_style), Paragraph("12333,0", table_cell_style), Paragraph("267,7", table_cell_style), Paragraph("2014,7", table_cell_style), Paragraph("1105,9", table_cell_style), Paragraph("1322,5", table_cell_style), Paragraph("1403,6", table_cell_style), Paragraph("1418,9", table_cell_style)],
        [Paragraph("7 (Proa)", table_cell_style), Paragraph("14800,0", table_cell_style), Paragraph("2537,1", table_cell_style), Paragraph("2537,1", table_cell_style), Paragraph("0,0", table_cell_style), Paragraph("0,0", table_cell_style), Paragraph("0,0", table_cell_style), Paragraph("0,0", table_cell_style)]
    ]

    cotas_table = Table(cotas_data, colWidths=[25*mm, 32*mm, 32*mm, 32*mm, 38*mm, 38*mm, 38*mm, 38*mm])
    cotas_table.setStyle(TableStyle([
        ('BACKGROUND', (0,0), (-1,0), primary_color),
        ('ALIGN', (0,0), (-1,-1), 'CENTER'),
        ('VALIGN', (0,0), (-1,-1), 'MIDDLE'),
        ('GRID', (0,0), (-1,-1), 0.4, colors.HexColor("#CBD5E0")),
        ('ROWBACKGROUNDS', (0,1), (-1,-1), [colors.white, light_bg]),
        ('PADDING', (0,0), (-1,-1), 1.2),
    ]))
    story.append(cotas_table)
    story.append(Spacer(1, 2))

    # Imagem da Prancha Técnica 3D
    img_path = '/home/magdalena/eee/grupos/grupo-3/Projeto_3D_Plano_Linhas_Saveiro_14_80m.png'
    if os.path.exists(img_path):
        # A4 Landscape printable width ~ 273mm, height ajustada para caber em 1 página
        img = Image(img_path, width=270*mm, height=120*mm)
        story.append(img)

    doc.build(story, canvasmaker=NumberedCanvasLandscape)

if __name__ == '__main__':
    out_pdf = '/home/magdalena/eee/grupos/grupo-3/Prancha_3D_Plano_Linhas_Saveiro_14_80m.pdf'
    build_prancha_pdf(out_pdf)
    print("PDF Prancha 3D gerado com sucesso.")
