import os
import sys
from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.platypus import (
    SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, PageBreak, KeepTogether, HRFlowable
)
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.pdfgen import canvas

class NumberedCanvas(canvas.Canvas):
    def __init__(self, *args, **kwargs):
        super(NumberedCanvas, self).__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_page_number(num_pages)
            super(NumberedCanvas, self).showPage()
        super(NumberedCanvas, self).save()

    def draw_page_number(self, page_count):
        self.saveState()
        self.setFont("Helvetica", 9)
        self.setFillColor(colors.HexColor("#4A5568"))
        
        # Header (pages > 1)
        if self._pageNumber > 1:
            self.drawString(54, 800, "Brana Escola de Engenharia Naval | Estaleiro Escola Embrião (EEE)")
            self.drawRightString(541, 800, "Coeficientes de Forma — Casco Quinado 4,00m — Matheus Silva")
            self.setStrokeColor(colors.HexColor("#CBD5E0"))
            self.setLineWidth(0.5)
            self.line(54, 792, 541, 792)
            
        # Footer
        text = f"Página {self._pageNumber} de {page_count}"
        self.drawRightString(541, 36, text)
        self.drawString(54, 36, "Projeto: Matheus Silva — Prof. Assistente: Magdalena (Mada)")
        self.setStrokeColor(colors.HexColor("#CBD5E0"))
        self.setLineWidth(0.5)
        self.line(54, 48, 541, 48)
        self.restoreState()

def build_pdf(filename):
    doc = SimpleDocTemplate(
        filename,
        pagesize=A4,
        leftMargin=54,
        rightMargin=54,
        topMargin=54,
        bottomMargin=54
    )

    styles = getSampleStyleSheet()
    
    primary_color = colors.HexColor("#0F3E6D")
    secondary_color = colors.HexColor("#1D70B8")
    dark_neutral = colors.HexColor("#1A202C")
    light_bg = colors.HexColor("#F7FAFC")
    accent_color = colors.HexColor("#9A3231") # Vermelho Brana

    title_style = ParagraphStyle(
        'DocTitle',
        parent=styles['Normal'],
        fontName='Helvetica-Bold',
        fontSize=20,
        leading=24,
        textColor=primary_color,
        spaceAfter=4
    )
    
    subtitle_style = ParagraphStyle(
        'DocSubTitle',
        parent=styles['Normal'],
        fontName='Helvetica',
        fontSize=11,
        leading=14,
        textColor=secondary_color,
        spaceAfter=10
    )

    h1_style = ParagraphStyle(
        'Heading1_Custom',
        parent=styles['Normal'],
        fontName='Helvetica-Bold',
        fontSize=12.5,
        leading=15,
        textColor=primary_color,
        spaceBefore=10,
        spaceAfter=4,
        keepWithNext=True
    )

    body_style = ParagraphStyle(
        'Body_Custom',
        parent=styles['Normal'],
        fontName='Helvetica',
        fontSize=9,
        leading=12.5,
        textColor=dark_neutral,
        spaceAfter=5
    )

    bullet_style = ParagraphStyle(
        'Bullet_Custom',
        parent=body_style,
        leftIndent=12,
        firstLineIndent=-8,
        spaceAfter=2
    )

    story = []

    # Title & Header
    story.append(Paragraph("MEMORIAL DE COEFICIENTES DE FORMA E HIDROSTÁTICA", title_style))
    story.append(Paragraph("Casco Quinado 4,00 m — Extraído do Plano de Linhas Oficial Brana", subtitle_style))
    story.append(HRFlowable(width="100%", thickness=2, color=accent_color, spaceAfter=8))

    # Meta Info Table
    meta_data = [
        [
            Paragraph("<b>Aluno / Projetista:</b> Matheus Silva", body_style),
            Paragraph("<b>Orientação Técnica:</b> Profa. Magdalena (Mada)", body_style)
        ],
        [
            Paragraph("<b>Instituição:</b> Brana & Estaleiro Escola Embrião (EEE)", body_style),
            Paragraph("<b>DWL de Projeto (Calado):</b> 291 mm", body_style)
        ],
        [
            Paragraph("<b>Geometria de Referência:</b> Plano-de-Linhas-Matheus-Silva.pdf", body_style),
            Paragraph("<b>Tipo de Casco:</b> Quinado (Hard Chine / 8 balizas)", body_style)
        ]
    ]
    t_meta = Table(meta_data, colWidths=[240, 240])
    t_meta.setStyle(TableStyle([
        ('BACKGROUND', (0,0), (-1,-1), light_bg),
        ('BOX', (0,0), (-1,-1), 0.5, colors.HexColor("#CBD5E0")),
        ('INNERGRID', (0,0), (-1,-1), 0.5, colors.HexColor("#E2E8F0")),
        ('TOPPADDING', (0,0), (-1,-1), 3),
        ('BOTTOMPADDING', (0,0), (-1,-1), 3),
        ('LEFTPADDING', (0,0), (-1,-1), 6),
        ('RIGHTPADDING', (0,0), (-1,-1), 6),
    ]))
    story.append(t_meta)
    story.append(Spacer(1, 6))

    # 1. Dimensões Principais do Plano de Linhas
    story.append(Paragraph("1. Dimensões Principais na Linha d'Água de Projeto (DWL = 291 mm)", h1_style))
    
    dim_data = [
        [Paragraph("<b>Grandeza Geométrica</b>", body_style), Paragraph("<b>Símbolo</b>", body_style), Paragraph("<b>Valor (mm / m)</b>", body_style), Paragraph("<b>Observações</b>", body_style)],
        [Paragraph("Comprimento Total", body_style), Paragraph("LOA", body_style), Paragraph("<b>4.000 mm (4,00 m)</b>", body_style), Paragraph("Extremidade de popa à roda de proa", body_style)],
        [Paragraph("Comprimento na Linha d'Água", body_style), Paragraph("LWL", body_style), Paragraph("<b>3.626 mm (3,63 m)</b>", body_style), Paragraph("Balanço de proa = 150 mm / Popa = 0 mm", body_style)],
        [Paragraph("Boca Máxima Moldada", body_style), Paragraph("BOA", body_style), Paragraph("<b>1.546 mm (1,55 m)</b>", body_style), Paragraph("Meia-nau na borda livre (Baliza 4)", body_style)],
        [Paragraph("Boca na Linha d'Água", body_style), Paragraph("BWL", body_style), Paragraph("<b>1.281 mm (1,28 m)</b>", body_style), Paragraph("Largura do plano de flutuação na DWL", body_style)],
        [Paragraph("Pontal Moldado", body_style), Paragraph("D", body_style), Paragraph("<b>729 mm (0,73 m)</b>", body_style), Paragraph("Altura da linha de base à borda", body_style)],
        [Paragraph("Calado de Projeto", body_style), Paragraph("T (DWL)", body_style), Paragraph("<b>291 mm (0,29 m)</b>", body_style), Paragraph("40% do pontal de projeto", body_style)],
        [Paragraph("Borda Livre Mínima", body_style), Paragraph("F", body_style), Paragraph("<b>438 mm (0,44 m)</b>", body_style), Paragraph("D - T a meia-nau", body_style)]
    ]
    t_dim = Table(dim_data, colWidths=[140, 50, 110, 180])
    t_dim.setStyle(TableStyle([
        ('BACKGROUND', (0,0), (-1,0), primary_color),
        ('TEXTCOLOR', (0,0), (-1,0), colors.white),
        ('GRID', (0,0), (-1,-1), 0.5, colors.HexColor("#CBD5E0")),
        ('ROWBACKGROUNDS', (0,1), (-1,-1), [colors.white, light_bg]),
        ('TOPPADDING', (0,0), (-1,-1), 2.5),
        ('BOTTOMPADDING', (0,0), (-1,-1), 2.5),
    ]))
    story.append(t_dim)
    story.append(Spacer(1, 6))

    # 2. Tabela de Coeficientes de Forma
    story.append(Paragraph("2. Coeficientes de Forma e Propriedades Hidrostáticas", h1_style))
    
    coef_data = [
        [Paragraph("<b>Coeficiente / Propriedade</b>", body_style), Paragraph("<b>Símbolo</b>", body_style), Paragraph("<b>Fórmula</b>", body_style), Paragraph("<b>Valor de Projeto</b>", body_style), Paragraph("<b>Significado Naval</b>", body_style)],
        [Paragraph("<b>Coeficiente de Bloco</b>", body_style), Paragraph("Cb", body_style), Paragraph("∇ / (Lwl × Bwl × T)", body_style), Paragraph("<b>0,480</b>", body_style), Paragraph("Casco esguio de deslocamento, baixa resistência de onda", body_style)],
        [Paragraph("<b>Coeficiente Seção Mestra</b>", body_style), Paragraph("Cm", body_style), Paragraph("Am / (Bwl × T)", body_style), Paragraph("<b>0,602</b>", body_style), Paragraph("Fundo em V com deadrise moderado (19,75° na meia-nau)", body_style)],
        [Paragraph("<b>Coeficiente Prismático</b>", body_style), Paragraph("Cp", body_style), Paragraph("Cb / Cm", body_style), Paragraph("<b>0,797</b>", body_style), Paragraph("Volume distribuído para cruzeiro sustentado", body_style)],
        [Paragraph("<b>Coef. Plano Flutuação</b>", body_style), Paragraph("Cwp", body_style), Paragraph("Awp / (Lwl × Bwl)", body_style), Paragraph("<b>0,712</b>", body_style), Paragraph("Plano d'água amplo a ré garantindo estabilidade de forma", body_style)],
        [Paragraph("<b>Deslocamento Volumétrico</b>", body_style), Paragraph("∇", body_style), Paragraph("Integral da Curva Áreas", body_style), Paragraph("<b>0,6472 m³</b>", body_style), Paragraph("Volume de carena submerso exato na DWL", body_style)],
        [Paragraph("<b>Deslocamento em Massa (Sal)</b>", body_style), Paragraph("Δ", body_style), Paragraph("∇ × 1,025 t/m³", body_style), Paragraph("<b>663 kg</b>", body_style), Paragraph("Peso total em ordem de marcha para água do mar", body_style)],
        [Paragraph("<b>Área Máxima Seção Mestra</b>", body_style), Paragraph("Am", body_style), Paragraph("Seção Baliza 4", body_style), Paragraph("<b>0,224 m²</b>", body_style), Paragraph("Área submersa máxima transversal", body_style)]
    ]
    t_coef = Table(coef_data, colWidths=[120, 45, 105, 75, 135])
    t_coef.setStyle(TableStyle([
        ('BACKGROUND', (0,0), (-1,0), secondary_color),
        ('TEXTCOLOR', (0,0), (-1,0), colors.white),
        ('GRID', (0,0), (-1,-1), 0.5, colors.HexColor("#CBD5E0")),
        ('ROWBACKGROUNDS', (0,1), (-1,-1), [colors.white, light_bg]),
        ('TOPPADDING', (0,0), (-1,-1), 2.5),
        ('BOTTOMPADDING', (0,0), (-1,-1), 2.5),
    ]))
    story.append(t_coef)
    story.append(Spacer(1, 8))

    # 3. Análise dos Coeficientes e Comportamento
    story.append(Paragraph("3. Análise Técnica e Comportamento do Casco", h1_style))
    story.append(Paragraph("• <b>Relação Adimensional LOA / BOA = 2,59:</b> Proporciona excelente estabilidade transversal inicial, ideal para embarcações de pequeno porte com movimentação a bordo.", bullet_style))
    story.append(Paragraph("• <b>Deadrise Variável (V-Bottom):</b> Ângulo de V que evolui de 36,01° na baliza 7 (proa) para 19,75° na meia-nau e 26,77° na baliza 1 (popa), assegurando entrada macia na onda e boa sustentação hidrodinâmica.", bullet_style))
    story.append(Paragraph("• <b>Concordância Hidrostática:</b> A integração numérica da curva de áreas das 8 balizas converge a 100% com o volume tridimensional ($0,6472\text{ m}^3$), atestando a consistência geométrica entre o Plano de Linhas e o modelo 3D.", bullet_style))

    doc.build(story, canvasmaker=NumberedCanvas)
    print("PDF de Coeficientes de Forma gerado com sucesso!")

if __name__ == "__main__":
    pdf_path = "/home/magdalena/eee/alunos/matheus-silva/Coeficientes_de_Forma_Matheus_Silva.pdf"
    build_pdf(pdf_path)
