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

class NumberedCanvas(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", 8)
        self.setFillColor(colors.HexColor("#1A365D")) # Navy
        
        # Header (pages > 1)
        if self._pageNumber > 1:
            self.drawString(20*mm, 282*mm, "BRANA / EEE - PROJETO CATAMARÃ OCEÂNICO 45'")
            self.setFont("Helvetica", 8)
            self.setFillColor(colors.HexColor("#4A5568"))
            self.drawRightString(190*mm, 282*mm, "Vera Cruz (BA) ➔ África do Sul")
            self.setStrokeColor(colors.HexColor("#CBD5E0"))
            self.setLineWidth(0.5)
            self.line(20*mm, 280*mm, 190*mm, 280*mm)

        # Footer
        self.setStrokeColor(colors.HexColor("#CBD5E0"))
        self.setLineWidth(0.5)
        self.line(20*mm, 18*mm, 190*mm, 18*mm)
        
        self.setFont("Helvetica", 8)
        self.setFillColor(colors.HexColor("#718096"))
        self.drawString(20*mm, 12*mm, "Professora Assistente: Magdalena (Mada) | Aluno: Rodolfo G. Giordano")
        page_str = f"Página {self._pageNumber} de {page_count}"
        self.drawRightString(190*mm, 12*mm, page_str)
        self.restoreState()

def generate_pdf(output_path):
    doc = SimpleDocTemplate(
        output_path,
        pagesize=A4,
        leftMargin=20*mm,
        rightMargin=20*mm,
        topMargin=22*mm,
        bottomMargin=22*mm
    )

    styles = getSampleStyleSheet()
    
    # Custom Styles
    primary_color = colors.HexColor("#1A365D")   # Deep Navy
    secondary_color = colors.HexColor("#2B6CB0") # Marine Blue
    accent_color = colors.HexColor("#C53030")    # Dark Red / Alert
    dark_neutral = colors.HexColor("#2D3748")    # Charcoal text
    light_bg = colors.HexColor("#F7FAFC")        # Soft Grey background

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

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

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

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

    bullet_style = ParagraphStyle(
        'BulletDark',
        parent=body_style,
        leftIndent=12,
        bulletIndent=4,
        spaceAfter=4
    )

    callout_style = ParagraphStyle(
        'CalloutText',
        parent=styles['Normal'],
        fontName='Helvetica-Oblique',
        fontSize=9,
        leading=13,
        textColor=colors.HexColor("#2C5282")
    )

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

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

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

    story = []

    # Title Banner Block
    story.append(Paragraph("RELATÓRIO TÉCNICO DE PROJETO & NAVEGAÇÃO", subtitle_style))
    story.append(Paragraph("Catamarã Oceânico 45' — Travessia Bahia ➔ África do Sul", title_style))
    story.append(HRFlowable(width="100%", thickness=1.5, color=primary_color, spaceBefore=4, spaceAfter=10))

    # Info Box Metadata Table
    info_data = [
        [
            Paragraph("<b>Aluno:</b> Rodolfo G. Giordano", table_cell_style),
            Paragraph("<b>Instituição:</b> Brana / Estaleiro Escola Embrião", table_cell_style),
            Paragraph("<b>Data:</b> Setembro / 2026", table_cell_style)
        ],
        [
            Paragraph("<b>Embarcação:</b> Catamarã a Vela 45 ft", table_cell_style),
            Paragraph("<b>Tripulação:</b> 3 pessoas + 2 cães", table_cell_style),
            Paragraph("<b>Apêndices:</b> Quilhas Rasas Fixas", table_cell_style)
        ]
    ]
    info_table = Table(info_data, colWidths=[55*mm, 60*mm, 55*mm])
    info_table.setStyle(TableStyle([
        ('BACKGROUND', (0,0), (-1,-1), colors.HexColor("#EDF2F7")),
        ('PADDING', (0,0), (-1,-1), 5),
        ('BOX', (0,0), (-1,-1), 0.5, colors.HexColor("#CBD5E0")),
        ('VALIGN', (0,0), (-1,-1), 'MIDDLE'),
    ]))
    story.append(info_table)
    story.append(Spacer(1, 10))

    # Section 1: Enquadramento e Áreas de Navegação
    story.append(Paragraph("1. Enquadramento e Classificação das Áreas de Navegação", h1_style))
    story.append(Paragraph(
        "A definição correta das áreas de navegação rege todos os requisitos legais da Autoridade Marítima (NORMAM) "
        "e os critérios de estabilidade e integridade estrutural (norma internacional ISO 12217-2).", body_style
    ))

    nav_table_data = [
        [
            Paragraph("Trecho da Rota", table_header_style),
            Paragraph("Classificação NORMAM", table_header_style),
            Paragraph("Cat. ISO 12217", table_header_style),
            Paragraph("Exigências e Foco Técnico", table_header_style)
        ],
        [
            Paragraph("<b>Vera Cruz ➔ Barra de Salvador</b>", table_cell_bold),
            Paragraph("Navegação Interior (Área 1 - Abrigada)", table_cell_style),
            Paragraph("Cat. C / D", table_cell_style),
            Paragraph("Atenção ao calado e bancos de areia na saída da Baía de Todos-os-Santos.", table_cell_style)
        ],
        [
            Paragraph("<b>Saída da Barra ➔ 20 MN</b>", table_cell_bold),
            Paragraph("Mar Aberto - Costeira", table_cell_style),
            Paragraph("Cat. B", table_cell_style),
            Paragraph("VHF Marítimo, monitoramento do tráfego e transição de plataforma continental.", table_cell_style)
        ],
        [
            Paragraph("<b>Travessia Oceânica (Bahia ➔ Cape Town)</b>", table_cell_bold),
            Paragraph("Mar Aberto - Oceânica (Sem Limites)", table_cell_style),
            Paragraph("Cat. A (Oceânica)", table_cell_style),
            Paragraph("Ventos > 40 nós, ondas > 4 m. Balsa Classe A, EPIRB, SART, Linhas de Vida e Dessalinizador.", table_cell_style)
        ],
        [
            Paragraph("<b>Costa Sul-Africana (Cape Town ➔ Jeffreys Bay)</b>", table_cell_bold),
            Paragraph("Mar Aberto - Costeira / Oceânica", table_cell_style),
            Paragraph("Cat. A", table_cell_style),
            Paragraph("Interação crítica da Corrente das Agulhas contra frentes frias de SW.", table_cell_style)
        ],
    ]
    
    nav_table = Table(nav_table_data, colWidths=[40*mm, 42*mm, 23*mm, 65*mm])
    nav_table.setStyle(TableStyle([
        ('BACKGROUND', (0,0), (-1,0), primary_color),
        ('ALIGN', (0,0), (-1,-1), 'LEFT'),
        ('VALIGN', (0,0), (-1,-1), 'TOP'),
        ('GRID', (0,0), (-1,-1), 0.5, colors.HexColor("#CBD5E0")),
        ('ROWBACKGROUNDS', (0,1), (-1,-1), [colors.white, light_bg]),
        ('PADDING', (0,0), (-1,-1), 4.5),
    ]))
    story.append(nav_table)
    story.append(Spacer(1, 10))

    # Section 2: Climatologia e Melhores Épocas
    story.append(Paragraph("2. Climatologia e Melhores Épocas para a Travessia", h1_style))
    
    callout_data = [[
        Paragraph(
            "<b>Janela Ideal de Saída:</b> <b>Novembro a Fevereiro / Março (Verão do Hemisfério Sul)</b>.<br/>"
            "<i>Justificativa Sinótica:</i> No verão austral, a Alta Subtropical de Santa Helena desloca-se para sul (~30°S–35°S), "
            "e o cinturão de tempestades antárticas afasta-se do Cabo da Boa Esperança, garantindo ventos portantes consistentes e mar mais ameno.",
            callout_style
        )
    ]]
    callout_table = Table(callout_data, colWidths=[170*mm])
    callout_table.setStyle(TableStyle([
        ('BACKGROUND', (0,0), (-1,-1), colors.HexColor("#EBF8FF")),
        ('BOX', (0,0), (-1,-1), 1, colors.HexColor("#63B3ED")),
        ('PADDING', (0,0), (-1,-1), 6),
    ]))
    story.append(callout_table)
    story.append(Spacer(1, 8))

    story.append(Paragraph("<b>Riscos Críticos de Época Fora da Janela (Inverno: Maio a Setembro):</b>", body_style))
    story.append(Paragraph("• Ciclones extratropicais frequentes ao sul do paralelo 30°S com frentes frias violentas.", bullet_style))
    story.append(Paragraph("• Ondas oceânicas com altura significativa frequentemente excedendo 6 a 8 metros no Cabo.", bullet_style))
    story.append(Paragraph("• Temperaturas severamente baixas na chegada à Corrente de Benguela e África do Sul.", bullet_style))
    
    story.append(Spacer(1, 10))

    # Section 3: Planejamento Estratégico de Rotas
    story.append(Paragraph("3. Planejamento Estratégico de Rotas", h1_style))
    
    story.append(Paragraph("Trecho 1: Vera Cruz (BA) ➔ Cape Town (~3.600 a 3.800 MN)", h2_style))
    story.append(Paragraph(
        "A travessia à vela não é realizada em linha reta (rota loxodrômica direta) para evitar a calmaria "
        "no centro da Alta Subtropical. A rota divide-se em três etapas estratégicas:", body_style
    ))
    story.append(Paragraph("<b>1. Saída da Bahia (13°S ➔ 25°S):</b> Navegação para SSE/SE em ventos alísios favoráveis de E/NE.", bullet_style))
    story.append(Paragraph("<b>2. Arco do Atlântico Sul (25°S ➔ 34°S):</b> Curva para leste na esteira dos ventos de Oeste (<i>Westerlies</i>), mantendo excelente velocidade média com mar de popa/alheta.", bullet_style))
    story.append(Paragraph("<b>3. Aproximação do Cabo (34°S):</b> Subida gradual para Table Bay com apoio da Corrente de Benguela. Tempo estimado de viagem: <b>20 a 25 dias</b> (média de 6,5 a 7,5 nós).", bullet_style))

    story.append(Spacer(1, 6))

    story.append(Paragraph("Trecho 2: Costa Sul-Africana — Cape Town ➔ Port Elizabeth / Jeffreys Bay (~450 MN)", h2_style))
    story.append(Paragraph(
        "Trecho de altíssima exigência técnica náutica. A <b>Corrente das Agulhas</b> corre para SW com velocidade de 3 a 5 nós. "
        "Quando ventos de SW (frentes frias) sopram contra a corrente, formam-se ondas anômalas (*freak waves*) perigosas.", body_style
    ))
    story.append(Paragraph("• <b>Estratégia:</b> Navegar exclusivamente em janelas curtas de 24h a 48h com ventos fracos ou de quadrante Leste.", bullet_style))
    story.append(Paragraph("• <b>Tática de Carta:</b> Manter-se na plataforma interna costeira para escapar do núcleo principal da corrente.", bullet_style))
    story.append(Paragraph("• <b>Portos de Refúgio:</b> Hout Bay, Simon's Town, Mossel Bay e Knysna.", bullet_style))

    story.append(Spacer(1, 10))

    # Section 4: Especificações Preliminares do Catamarã 45'
    story.append(Paragraph("4. Especificações Preliminares do Projeto (Catamarã 45')", h1_style))

    spec_data = [
        [Paragraph("Parâmetro de Projeto", table_header_style), Paragraph("Dimensão / Especificação", table_header_style), Paragraph("Impacto na Missão Oceânica", table_header_style)],
        [Paragraph("Comprimento Total (LOA)", table_cell_bold), Paragraph("13,72 m (45,0 ft)", table_cell_style), Paragraph("Excelente volume interno para 3 pessoas e 2 cães com autonomia.", table_cell_style)],
        [Paragraph("Linha d'Água (LWL)", table_cell_bold), Paragraph("13,20 m", table_cell_style), Paragraph("Relação LWL/LOA alta para elevar velocidade crítica de casco.", table_cell_style)],
        [Paragraph("Boca Total (BOA)", table_cell_bold), Paragraph("7,50 m (B/L ≈ 0,55)", table_cell_style), Paragraph("Momento restaurador elevado e estabilidade de forma exemplar.", table_cell_style)],
        [Paragraph("Calado (Draft)", table_cell_bold), Paragraph("1,25 m", table_cell_style), Paragraph("Quilhas rasas de sacrifício (*minikeels*); proteção de lemes e eixos.", table_cell_style)],
        [Paragraph("Vão Central (*Clearance*)", table_cell_bold), Paragraph("0,85 m a 0,90 m", table_cell_style), Paragraph("Elimina o impacto violento de ondas (*slamming*) no fundo da cabine.", table_cell_style)],
        [Paragraph("Deslocamento Máximo", table_cell_bold), Paragraph("13.800 kg (Carga: ~3.800 kg)", table_cell_style), Paragraph("Margem segura para água, diesel, mantimentos de 35+ dias e pets.", table_cell_style)],
        [Paragraph("Motorização Auxiliar", table_cell_bold), Paragraph("2 x 45 hp Diesel (Saildrive)", table_cell_style), Paragraph("Redundância oceânica e autonomia a motor de ~500 milhas náuticas.", table_cell_style)],
        [Paragraph("Energia & Água", table_cell_bold), Paragraph("Solar 1.500Wp + LiFePO4 + Dessal.", table_cell_style), Paragraph("Independência energética total durante a travessia de 25 dias.", table_cell_style)]
    ]

    spec_table = Table(spec_data, colWidths=[45*mm, 50*mm, 75*mm])
    spec_table.setStyle(TableStyle([
        ('BACKGROUND', (0,0), (-1,0), primary_color),
        ('ALIGN', (0,0), (-1,-1), 'LEFT'),
        ('VALIGN', (0,0), (-1,-1), 'MIDDLE'),
        ('GRID', (0,0), (-1,-1), 0.5, colors.HexColor("#CBD5E0")),
        ('ROWBACKGROUNDS', (0,1), (-1,-1), [colors.white, light_bg]),
        ('PADDING', (0,0), (-1,-1), 4),
    ]))
    story.append(spec_table)

    story.append(Spacer(1, 10))

    # Section 5: Adaptações para Cães e Segurança
    story.append(Paragraph("5. Requisitos Especiais de Segurança e Vida a Bordo", h1_style))
    story.append(Paragraph("• <b>Linhas de Vida e Proteção Periférica:</b> Guarda-mancebo com tela de proteção rígida em aço inox ou rede de alta tenacidade em todo o convés e trampolim.", bullet_style))
    story.append(Paragraph("• <b>Cockpit em Nível Único (*Single-Level Living*):</b> Transição sem degraus íngremes entre salão e praça de popa, garantindo estabilidade e locomoção segura para os cães.", bullet_style))
    story.append(Paragraph("• <b>Estanqueidade e Segurança Passiva:</b> Escotilhas de fuga (*escape hatches*) nos costados internos dos cascos e anteparas de colisão estanques na proa e popa.", bullet_style))

    doc.build(story, canvasmaker=NumberedCanvas)

if __name__ == '__main__':
    output_pdf = '/home/magdalena/eee/alunos/rodolfo-g-giordano/Relatorio_Navegacao_Catamara_45_Rodolfo_Giordano.pdf'
    generate_pdf(output_pdf)
    print(f"PDF generated successfully at: {output_pdf}")
