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
)
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 — ESTUDO DE SIMILARES (GRUPO 3)")
        self.setFont("Helvetica", 7.5)
        self.setFillColor(colors.HexColor("#4A5568"))
        self.drawRightString(285*mm, 200*mm, "Saveiros Tradicionais da BTS vs. Saveiro Híbrido 'Mestre da Cana' (Deslocamento 26 t) · 15/10/2026")
        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, 8*mm, 285*mm, 8*mm)
        
        self.setFont("Helvetica", 7.5)
        self.setFillColor(colors.HexColor("#718096"))
        self.drawString(12*mm, 5.0*mm, "Professora Assistente: Magdalena (Mada) | Brana Projetos Navais & EEE | Aluno: Air (Grupo 3)")
        page_str = f"Página {self._pageNumber} de {page_count}"
        self.drawRightString(285*mm, 5.0*mm, page_str)
        self.restoreState()

def build_similares_pdf(output_paths):
    for output_path in output_paths:
        doc = SimpleDocTemplate(
            output_path,
            pagesize=landscape(A4),
            leftMargin=10*mm,
            rightMargin=10*mm,
            topMargin=11*mm,
            bottomMargin=10*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")        # Soft Grey background
        highlight_bg = colors.HexColor("#FEFCBF")    # Soft Yellow highlight

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

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

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

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

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

        table_cell_left = ParagraphStyle(
            'TableCellLeft',
            parent=styles['Normal'],
            fontName='Helvetica',
            fontSize=6.3,
            leading=7.8,
            textColor=dark_neutral,
            alignment=0
        )

        table_cell_bold = ParagraphStyle(
            'TableCellBold',
            parent=table_cell_style,
            fontName='Helvetica-Bold',
            textColor=primary_color
        )

        table_cell_proj = ParagraphStyle(
            'TableCellProj',
            parent=table_cell_style,
            fontName='Helvetica-Bold',
            textColor=colors.HexColor("#975A16")
        )

        story = []

        # Title & Subtitle
        story.append(Paragraph("ESTUDO DE SIMILARES E ANÁLISE COMPARATIVA DE ENGENHARIA NAVAL", subtitle_style))
        story.append(Paragraph("Saveiros Tradicionais de Vela de Içar da Bahia vs. Saveiro Híbrido 'Mestre da Cana' (Grupo 3)", title_style))
        story.append(HRFlowable(width="100%", thickness=0.8, color=primary_color, spaceBefore=1, spaceAfter=2.5))

        # Tabela Completa de Similares com Linhas D, d e D/d ajustadas para 26 t (26.278 kg)
        table_data = [
            [
                Paragraph("PARÂMETRO TÉCNICO", table_header_style),
                Paragraph("UNID.", table_header_style),
                Paragraph("Similar 1<br/>Dragão do Mar", table_header_style),
                Paragraph("Similar 2<br/>Vela Branca", table_header_style),
                Paragraph("Similar 3<br/>Bom Jesus Naveg.", table_header_style),
                Paragraph("Similar 4<br/>Dois Irmãos", table_header_style),
                Paragraph("MESTRE DA CANA<br/>(PROJETO GRUPO 3)", table_header_style)
            ],
            [
                Paragraph("<b>Tipo / Função Principal</b>", table_cell_left),
                Paragraph("—", table_cell_style),
                Paragraph("Saveiro Tradicional BTS", table_cell_style),
                Paragraph("Saveiro Tradicional BTS", table_cell_style),
                Paragraph("Saveiro Tradicional BTS", table_cell_style),
                Paragraph("Saveiro Tradicional BTS", table_cell_style),
                Paragraph("<b>Saveiro Multimodal Híbrido (Economia Verde)</b>", table_cell_proj)
            ],
            [
                Paragraph("<b>Lotação / Tripulação</b>", table_cell_left),
                Paragraph("Pessoas", table_cell_style),
                Paragraph("8 a 10", table_cell_style),
                Paragraph("10 a 12", table_cell_style),
                Paragraph("6 a 8", table_cell_style),
                Paragraph("8 a 10", table_cell_style),
                Paragraph("<b>3 (Carga) / 40 (Turismo Pedagógico)</b>", table_cell_proj)
            ],
            [
                Paragraph("<b>Comprimento Total (LOA)</b>", table_cell_left),
                Paragraph("m", table_cell_style),
                Paragraph("13,70", table_cell_style),
                Paragraph("14,00", table_cell_style),
                Paragraph("13,50", table_cell_style),
                Paragraph("13,80", table_cell_style),
                Paragraph("<b>14,80</b>", table_cell_proj)
            ],
            [
                Paragraph("<b>Comprimento Linha d'Água (LWL)</b>", table_cell_left),
                Paragraph("m", table_cell_style),
                Paragraph("12,30", table_cell_style),
                Paragraph("13,00", table_cell_style),
                Paragraph("12,20", table_cell_style),
                Paragraph("12,60", table_cell_style),
                Paragraph("<b>12,88 (Plano Vélico: 12,876)</b>", table_cell_proj)
            ],
            [
                Paragraph("<b>Boca Máxima (BOA / BWL)</b>", table_cell_left),
                Paragraph("m", table_cell_style),
                Paragraph("4,50", table_cell_style),
                Paragraph("4,80", table_cell_style),
                Paragraph("4,30", table_cell_style),
                Paragraph("4,60", table_cell_style),
                Paragraph("<b>4,90 (BWL: 4,63)</b>", table_cell_proj)
            ],
            [
                Paragraph("<b>Pontal Moldado (D)</b>", table_cell_left),
                Paragraph("m", table_cell_style),
                Paragraph("1,60", table_cell_style),
                Paragraph("2,00", table_cell_style),
                Paragraph("1,85", table_cell_style),
                Paragraph("1,80", table_cell_style),
                Paragraph("<b>1,90</b>", table_cell_proj)
            ],
            [
                Paragraph("<b>Calado do Casco (d / T)</b>", table_cell_left),
                Paragraph("m", table_cell_style),
                Paragraph("1,10", table_cell_style),
                Paragraph("1,35", table_cell_style),
                Paragraph("1,20", table_cell_style),
                Paragraph("1,20", table_cell_style),
                Paragraph("<b>1,00 (Quilha: 1,40 / Leme: 1,75)</b>", table_cell_proj)
            ],
            [
                Paragraph("<b>Razão Pontal / Calado (D / d)</b>", table_cell_left),
                Paragraph("—", table_cell_style),
                Paragraph("<b>1,45</b>", table_cell_bold),
                Paragraph("<b>1,48</b>", table_cell_bold),
                Paragraph("<b>1,54</b>", table_cell_bold),
                Paragraph("<b>1,50</b>", table_cell_bold),
                Paragraph("<b>1,90 (Borda livre: 0,90 m / 47%)</b>", table_cell_proj)
            ],
            [
                Paragraph("<b>Deslocamento Total (Δ)</b>", table_cell_left),
                Paragraph("kg", table_cell_style),
                Paragraph("~10.000", table_cell_style),
                Paragraph("11.000", table_cell_style),
                Paragraph("9.500", table_cell_style),
                Paragraph("10.500", table_cell_style),
                Paragraph("<b>26.278 (Leve: 15,3t / Carga: 11t)</b>", table_cell_proj)
            ],
            [
                Paragraph("<b>Capacidade de Carga Útil</b>", table_cell_left),
                Paragraph("ton", table_cell_style),
                Paragraph("~10,0 t", table_cell_style),
                Paragraph("11,0 t", table_cell_style),
                Paragraph("~9,5 t", table_cell_style),
                Paragraph("10,5 t", table_cell_style),
                Paragraph("<b>11,0 toneladas (Carga Polivalente BTS)</b>", table_cell_proj)
            ],
            [
                Paragraph("<b>Ângulo de V do Fundo (Deadrise)</b>", table_cell_left),
                Paragraph("graus", table_cell_style),
                Paragraph("~8°", table_cell_style),
                Paragraph("~7°", table_cell_style),
                Paragraph("~9°", table_cell_style),
                Paragraph("~8°", table_cell_style),
                Paragraph("<b>~8° (Cm = 0,741 / Cb = 0,430)</b>", table_cell_proj)
            ],
            [
                Paragraph("<b>Área Vélica Total (Vela de Içar)</b>", table_cell_left),
                Paragraph("m²", table_cell_style),
                Paragraph("100 m²", table_cell_style),
                Paragraph("110 m²", table_cell_style),
                Paragraph("95 m²", table_cell_style),
                Paragraph("105 m²", table_cell_style),
                Paragraph("<b>154,9 m² (Grande 122,6 + Buja 32,3)</b>", table_cell_proj)
            ],
            [
                Paragraph("<b>Motorização (Modelo / Tipo)</b>", table_cell_left),
                Paragraph("—", table_cell_style),
                Paragraph("Yanmar 3GM30 (3 cil.)", table_cell_style),
                Paragraph("Perkins 4.108 (4 cil.)", table_cell_style),
                Paragraph("MWM Diesel", table_cell_style),
                Paragraph("Yanmar 4JHE (4 cil.)", table_cell_style),
                Paragraph("<b>Híbrido Série: Elétrico 50kW + Gerador 25kVA</b>", table_cell_proj)
            ],
            [
                Paragraph("<b>Potência Instalada Total</b>", table_cell_left),
                Paragraph("HP", table_cell_style),
                Paragraph("30 HP", table_cell_style),
                Paragraph("40 HP", table_cell_style),
                Paragraph("25 HP", table_cell_style),
                Paragraph("35 HP", table_cell_style),
                Paragraph("<b>102 HP eq. (Elétrico 50kW + Gerador 25kVA)</b>", table_cell_proj)
            ],
            [
                Paragraph("<b>Combustível & Armazenamento</b>", table_cell_left),
                Paragraph("L / kWh", table_cell_style),
                Paragraph("80 – 100 L Diesel", table_cell_style),
                Paragraph("120 L Diesel", table_cell_style),
                Paragraph("70 – 80 L Diesel", table_cell_style),
                Paragraph("100 L Diesel", table_cell_style),
                Paragraph("<b>200 L Diesel + 48 kWh LiFePO4 + 5,5kWp Solar</b>", table_cell_proj)
            ],
            [
                Paragraph("<b>Velocidade (Cruzeiro / Máx.)</b>", table_cell_left),
                Paragraph("nós", table_cell_style),
                Paragraph("5–6 / 6–8 nós", table_cell_style),
                Paragraph("5–6 / 7 nós", table_cell_style),
                Paragraph("5 / 6 nós", table_cell_style),
                Paragraph("5–6 / 7 nós", table_cell_style),
                Paragraph("<b>5,5 / 7,2 nós (a vela até 8,5 nós)</b>", table_cell_proj)
            ],
            [
                Paragraph("<b>RAZÕES GEOMÉTRICAS & ADIMENSIONAIS</b>", table_cell_left),
                Paragraph("—", table_cell_style),
                Paragraph("—", table_cell_style),
                Paragraph("—", table_cell_style),
                Paragraph("—", table_cell_style),
                Paragraph("—", table_cell_style),
                Paragraph("—", table_cell_style)
            ],
            [
                Paragraph("<b>Razão LOA / BOA</b>", table_cell_left),
                Paragraph("—", table_cell_style),
                Paragraph("3,04", table_cell_style),
                Paragraph("2,92", table_cell_style),
                Paragraph("3,14", table_cell_style),
                Paragraph("3,00", table_cell_style),
                Paragraph("<b>3,02 (Média exata dos similares: 3,02)</b>", table_cell_proj)
            ],
            [
                Paragraph("<b>Razão Deslocamento / Área Vélica (Δ / SA)</b>", table_cell_left),
                Paragraph("kg/m²", table_cell_style),
                Paragraph("100,0", table_cell_style),
                Paragraph("100,0", table_cell_style),
                Paragraph("100,0", table_cell_style),
                Paragraph("100,0", table_cell_style),
                Paragraph("<b>169,7 (SA/∇^(2/3) = 17,7 — Cruzeiro Ágil)</b>", table_cell_proj)
            ],
            [
                Paragraph("<b>Razão Desloc.-Comprimento (DLR)</b>", table_cell_left),
                Paragraph("—", table_cell_style),
                Paragraph("149,8", table_cell_style),
                Paragraph("139,5", table_cell_style),
                Paragraph("145,8", table_cell_style),
                Paragraph("146,3", table_cell_style),
                Paragraph("<b>346,2 (Deslocamento Moderado / Marinheiro)</b>", table_cell_proj)
            ]
        ]

        sim_table = Table(table_data, colWidths=[52*mm, 12*mm, 40*mm, 40*mm, 40*mm, 40*mm, 53*mm])
        sim_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.35, colors.HexColor("#CBD5E0")),
            ('ROWBACKGROUNDS', (0,1), (-1,-1), [colors.white, light_bg]),
            ('BACKGROUND', (6,1), (6,-1), highlight_bg),
            ('BACKGROUND', (0,8), (-1,8), colors.HexColor("#EDF2F7")),
            ('BACKGROUND', (0,17), (-1,17), colors.HexColor("#CBD5E0")),
            ('PADDING', (0,0), (-1,-1), 1.2),
        ]))
        story.append(sim_table)
        story.append(Spacer(1, 2.5))

        story.append(Paragraph("Síntese Técnica e Justificativa de Projeto (Deslocamento de 26 t · Caso de Uso Oficial)", h1_style))
        story.append(Paragraph(
            "1. <b>Fidelidade Paramétrica (LOA/BOA = 3,02 e D/d = 1,90):</b> O <i>Mestre da Cana</i> preserva rigorosamente a razão clássica $L/B = 3,02$. Com calado de casco ajustado para $1,00\\text{ m}$ (deslocamento $26.278\\text{ kg}$), a borda livre amplia-se para <b>0,90 m</b> ($47\\%$ do pontal $D = 1,90\\text{ m}$), conferindo enorme segurança, reserva de flutuabilidade e excelente comportamento no mar da BTS.<br/>"
            "2. <b>Deslocamento Otimizado (26 t) & Razão DLR (346,2):</b> A transição para 26 t reduz o $DLR$ de 411 para 346,2, aproximando a esbeltez do casco dos saveiros tradicionais, com superfície molhada enxuta ($51,20\\text{ m}^2$) e arrasto de onda reduzido.<br/>"
            "3. <b>Plano Vélico & Estabilidade:</b> A área vélica desenhada de <b>154,87 m²</b> ($SA/\\nabla^{2/3} = 17,7$) proporciona cruzeiro potente com adernamento suave de apenas $6,87^\\circ$ (Dellenbaugh) e estabilidade estática formidável ($GM = 2,238\\text{ m}$ e $AVS = 110^\\circ$).",
            body_style
        ))

        doc.build(story, canvasmaker=NumberedCanvasLandscape)

if __name__ == '__main__':
    paths = [
        '/home/magdalena/eee/alunos/air/Estudo_de_Similares_Completo_Grupo_3.pdf',
        '/home/magdalena/eee/grupos/grupo-3/Estudo_de_Similares_Completo_Grupo_3.pdf',
        '/home/magdalena/eee/grupos/grupo-3/Entrega Final/Estudo_de_Similares_Completo_Grupo_3.pdf'
    ]
    build_similares_pdf(paths)
    print("Estudo de Similares atualizado com 26 t em todas as pastas!")
