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, Image as RLImage
)
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, "Saveiro 31.5' Cruzeiro & Pesca — 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 Preliminar: 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("#00ADB5")

    title_style = ParagraphStyle(
        'DocTitle',
        parent=styles['Normal'],
        fontName='Helvetica-Bold',
        fontSize=22,
        leading=26,
        textColor=primary_color,
        spaceAfter=4
    )
    
    subtitle_style = ParagraphStyle(
        'DocSubTitle',
        parent=styles['Normal'],
        fontName='Helvetica',
        fontSize=12,
        leading=15,
        textColor=secondary_color,
        spaceAfter=12
    )

    h1_style = ParagraphStyle(
        'Heading1_Custom',
        parent=styles['Normal'],
        fontName='Helvetica-Bold',
        fontSize=14,
        leading=17,
        textColor=primary_color,
        spaceBefore=12,
        spaceAfter=6,
        keepWithNext=True
    )

    h2_style = ParagraphStyle(
        'Heading2_Custom',
        parent=styles['Normal'],
        fontName='Helvetica-Bold',
        fontSize=11,
        leading=14,
        textColor=secondary_color,
        spaceBefore=8,
        spaceAfter=4,
        keepWithNext=True
    )

    body_style = ParagraphStyle(
        'Body_Custom',
        parent=styles['Normal'],
        fontName='Helvetica',
        fontSize=9.5,
        leading=13.5,
        textColor=dark_neutral,
        spaceAfter=6
    )

    bullet_style = ParagraphStyle(
        'Bullet_Custom',
        parent=body_style,
        leftIndent=15,
        firstLineIndent=-10,
        spaceAfter=3
    )

    callout_style = ParagraphStyle(
        'CalloutText',
        parent=body_style,
        fontSize=9,
        leading=12.5,
        textColor=colors.HexColor("#2D3748")
    )

    story = []

    # Title & Header
    story.append(Paragraph("RELATÓRIO DE PROJETO PRELIMINAR", title_style))
    story.append(Paragraph("Saveiro Clássico-Moderno de Cruzeiro & Pesca em PRFV (31.5 pés)", subtitle_style))
    story.append(HRFlowable(width="100%", thickness=2, color=accent_color, spaceAfter=10))

    # Meta Info Table
    meta_data = [
        [
            Paragraph("<b>Aluno:</b> Matheus Silva", body_style),
            Paragraph("<b>Orientação:</b> Profa. Magdalena (Mada)", body_style)
        ],
        [
            Paragraph("<b>Escola / Projeto:</b> Brana & Estaleiro Escola Embrião (EEE)", body_style),
            Paragraph("<b>Data:</b> Setembro / 2026", body_style)
        ],
        [
            Paragraph("<b>Área de Operação:</b> Baía de Todos os Santos (Madre de Deus ↔ Salvador)", body_style),
            Paragraph("<b>Enquadramento:</b> Navegação Interior (Área 1 / Área 2)", 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), 4),
        ('BOTTOMPADDING', (0,0), (-1,-1), 4),
        ('LEFTPADDING', (0,0), (-1,-1), 8),
        ('RIGHTPADDING', (0,0), (-1,-1), 8),
    ]))
    story.append(t_meta)
    story.append(Spacer(1, 10))

    # 1. Resumo Executivo e Missão
    story.append(Paragraph("1. Resumo Executivo e Missão da Embarcação", h1_style))
    story.append(Paragraph(
        "O presente projeto compreende o desenvolvimento conceitual e preliminar de um <b>Saveiro Clássico-Moderno de 31,5 pés (9,60 m)</b>, "
        "construído em compósito de fibra de vidro (PRFV). O barco combina as linhas hidrodinâmicas tradicionais dos saveiros baianos "
        "com técnicas construtivas contemporâneas, visando duplo perfil operacional: <b>lazer diurno/pesca esportiva para até 10 passageiros</b> "
        "e <b>cruzeiro de pernoite com habitabilidade completa para 4 pessoas</b> navegando pela Baía de Todos os Santos (BTS).",
        body_style
    ))

    # 2. Área de Navegação
    story.append(Paragraph("2. Análise da Área de Navegação (BTS)", h1_style))
    story.append(Paragraph(
        "A rota padrão estabelecida conecta o município de <b>Madre de Deus à cidade de Salvador</b> (~18 a 22 NM), "
        "passando pelos canais abrigados das Ilhas dos Frades e de Maré, alcançando a bacia central da baía. "
        "As diretrizes hidrográficas e ambientais consideradas incluem:",
        body_style
    ))
    story.append(Paragraph("• <b>Regime de Ventos:</b> Predominância de Leste/Sudeste e Nordeste (10 a 18 nós), com rajadas vespertinas.", bullet_style))
    story.append(Paragraph("• <b>Estado do Mar:</b> Águas abrigadas nas ilhas e mar picado ('carneirinhos') de 0,6 m a 1,2 m na travessia central.", bullet_style))
    story.append(Paragraph("• <b>Marés e Calado:</b> Variação semidiurna de até 3,0 m em sizígia. O calado de projeto de <b>1,10 m</b> garante livre trânsito em baixios e praias.", bullet_style))
    story.append(Spacer(1, 8))

    # 3. Dimensões Principais e Coeficientes
    story.append(Paragraph("3. Dimensões Principais e Hidrostática Preliminar", h1_style))
    
    geo_data = [
        [Paragraph("<b>Parâmetro Geométrico</b>", body_style), Paragraph("<b>Valor de Projeto</b>", body_style), Paragraph("<b>Parâmetro Hidrostático</b>", body_style), Paragraph("<b>Valor Estimado</b>", body_style)],
        [Paragraph("Comprimento Total (LOA)", body_style), Paragraph("<b>9,60 m (31,5 ft)</b>", body_style), Paragraph("Deslocamento Carregado (Δ)", body_style), Paragraph("<b>4.800 kg (4,8 t)</b>", body_style)],
        [Paragraph("Comprimento Linha d'Água (LWL)", body_style), Paragraph("<b>8,90 m</b>", body_style), Paragraph("Coeficiente de Bloco Corpo (Cb)", body_style), Paragraph("<b>0,44</b>", body_style)],
        [Paragraph("Boca Máxima Moldada (B)", body_style), Paragraph("<b>3,25 m</b>", body_style), Paragraph("Coeficiente de Seção Mestra (Cm)", body_style), Paragraph("<b>0,62</b>", body_style)],
        [Paragraph("Boca na Linha d'Água (BWL)", body_style), Paragraph("<b>2,90 m</b>", body_style), Paragraph("Coeficiente Prismático (Cp)", body_style), Paragraph("<b>0,70</b>", body_style)],
        [Paragraph("Calado de Projeto (T)", body_style), Paragraph("<b>1,10 m</b>", body_style), Paragraph("Altura Metacêntrica (GMt)", body_style), Paragraph("<b>0,78 m</b> (Alta Estabilidade)", body_style)],
        [Paragraph("Pontal Moldado (D)", body_style), Paragraph("<b>1,60 m</b>", body_style), Paragraph("Pé-direito Casaria Central", body_style), Paragraph("<b>1,82 m</b>", body_style)]
    ]
    t_geo = Table(geo_data, colWidths=[130, 110, 130, 110])
    t_geo.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), 3),
        ('BOTTOMPADDING', (0,0), (-1,-1), 3),
    ]))
    story.append(t_geo)
    story.append(Spacer(1, 10))

    # Page Break for Technical Drawing & Layout
    story.append(PageBreak())

    story.append(Paragraph("4. Arranjo Geral e Habitabilidade", h1_style))
    story.append(Paragraph(
        "A distribuição interna foi concebida para maximizar o conforto durante pernoites prolongados, "
        "aliando um amplo cockpit aberto (com mais de 3,0 m livres) para até 10 tripulantes em passeios e pescarias diurnas.",
        body_style
    ))

    # Inserir imagem do arranjo geral
    img_path = "/home/magdalena/eee/alunos/matheus-silva/arranjo_geral.png"
    if os.path.exists(img_path):
        story.append(RLImage(img_path, width=480, height=340))
        story.append(Spacer(1, 10))

    story.append(Paragraph("<b>Detalhamento dos Compartimentos:</b>", h2_style))
    story.append(Paragraph("• <b>Cabine de Proa:</b> Cama de casal em 'V' (2,00 m x 1,60 m), paiol de amarra isolado por antepara estanque e armários embutidos.", bullet_style))
    story.append(Paragraph("• <b>Salão Central:</b> Sofás laterais estofados e mesa rebatível para 6 pessoas, convertendo em duas camas de solteiro adicionais.", bullet_style))
    story.append(Paragraph("• <b>Banheiro Fechado (Boreste):</b> Vaso sanitário elétrico marinho, cuba e chuveiro pressurizado de água doce.", bullet_style))
    story.append(Paragraph("• <b>Cozinha / Galley (Bombordo):</b> Fogão náutico de 2 bocas, pia de inox e geladeira náutica 12V de 80 litros.", bullet_style))
    story.append(Paragraph("• <b>Praça de Popa / Cockpit:</b> Convés aberto, geleira/caixa de peixe térmica embutida, bancos com paióis de salvatagem e chuveiro de popa.", bullet_style))
    story.append(Spacer(1, 8))

    # 5. Croqui Original e Análise de Similares
    story.append(Paragraph("5. Estudo de Similares e Autonomia", h1_style))
    
    sim_data = [
        [Paragraph("<b>Embarcação</b>", body_style), Paragraph("<b>LOA / Boca</b>", body_style), Paragraph("<b>Calado / Desloc.</b>", body_style), Paragraph("<b>Motor</b>", body_style), Paragraph("<b>Água / Diesel</b>", body_style)],
        [Paragraph("<b>Saveiro Matheus Silva</b>", body_style), Paragraph("<b>9,60 m / 3,25 m</b>", body_style), Paragraph("<b>1,10 m / 4,8 t</b>", body_style), Paragraph("<b>40 HP Diesel</b>", body_style), Paragraph("<b>220 L / 140 L</b>", body_style)],
        [Paragraph("Fisher 30 (UK)", body_style), Paragraph("9,14 m / 3,00 m", body_style), Paragraph("1,30 m / 6,6 t", body_style), Paragraph("36 HP Diesel", body_style), Paragraph("200 L / 180 L", body_style)],
        [Paragraph("Cornish Crabber 32", body_style), Paragraph("9,75 m / 3,10 m", body_style), Paragraph("1,15 m / 5,8 t", body_style), Paragraph("35 HP Diesel", body_style), Paragraph("180 L / 120 L", body_style)],
        [Paragraph("Traineira Lazer 31", body_style), Paragraph("9,45 m / 3,30 m", body_style), Paragraph("0,95 m / 4,6 t", body_style), Paragraph("75 HP Diesel", body_style), Paragraph("300 L / 250 L", body_style)],
        [Paragraph("Island Packet 31", body_style), Paragraph("9,45 m / 3,35 m", body_style), Paragraph("1,22 m / 5,0 t", body_style), Paragraph("30 HP Diesel", body_style), Paragraph("220 L / 130 L", body_style)],
    ]
    t_sim = Table(sim_data, colWidths=[120, 95, 95, 85, 85])
    t_sim.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), 3),
        ('BOTTOMPADDING', (0,0), (-1,-1), 3),
    ]))
    story.append(t_sim)
    story.append(Spacer(1, 10))

    # Page Break for Student Sketch
    croqui_path = "/home/magdalena/eee/alunos/matheus-silva/croqui_original_matheus_silva.jpg"
    if os.path.exists(croqui_path):
        story.append(PageBreak())
        story.append(Paragraph("6. Registro do Croqui Conceitual Original do Aluno", h1_style))
        story.append(Paragraph(
            "Registro do desenho conceitual a mão livre submetido por <b>Matheus Silva</b>, "
            "ilustrando a concepção inicial da casaria, plano vélico, motorização e arranjo de bordo:",
            body_style
        ))
        story.append(Spacer(1, 6))
        story.append(RLImage(croqui_path, width=440, height=330))
        story.append(Spacer(1, 15))

        story.append(Paragraph("7. Parecer da Professora Assistente", h1_style))
        story.append(Paragraph(
            "<i>\"O projeto apresenta excelente consistência técnica entre a missão pretendida (lazer/cruzeiro de pernoite e pesca na BTS) "
            "e as decisões de engenharia naval adotadas (relação LOA/B de 2,95, calado de 1,10 m e GMt de 0,78 m). "
            "A construção em PRFV garante baixa manutenção e alta durabilidade nas águas quentes da Baía de Todos os Santos, "
            "preservando a nobreza das linhas clássicas dos saveiros tradicionais.\"</i>",
            body_style
        ))

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

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