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, Image
)
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, "Casos de Uso, Rotas & Especificação")
            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 build_complete_pdf(output_path):
    doc = SimpleDocTemplate(
        output_path,
        pagesize=A4,
        leftMargin=20*mm,
        rightMargin=20*mm,
        topMargin=22*mm,
        bottomMargin=22*mm
    )

    styles = getSampleStyleSheet()
    
    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=18,
        leading=22,
        textColor=primary_color,
        spaceAfter=4
    )
    
    subtitle_style = ParagraphStyle(
        'DocSubTitle',
        parent=styles['Normal'],
        fontName='Helvetica-Bold',
        fontSize=10.5,
        leading=14,
        textColor=secondary_color,
        spaceAfter=10
    )

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

    h2_style = ParagraphStyle(
        'SectionH2',
        parent=styles['Normal'],
        fontName='Helvetica-Bold',
        fontSize=10,
        leading=13.5,
        textColor=secondary_color,
        spaceBefore=6,
        spaceAfter=3,
        keepWithNext=True
    )

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

    bullet_style = ParagraphStyle(
        'BulletDark',
        parent=body_style,
        leftIndent=10,
        bulletIndent=3,
        spaceAfter=3
    )

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

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

    table_cell_style = ParagraphStyle(
        'TableCell',
        parent=styles['Normal'],
        fontName='Helvetica',
        fontSize=8,
        leading=11,
        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("DOCUMENTO DE REQUISITOS, CASOS DE USO E NAVEGAÇÃO", subtitle_style))
    story.append(Paragraph("Catamarã Oceânico 45' — Vera Cruz (BA) ➔ África do Sul", title_style))
    story.append(HRFlowable(width="100%", thickness=1.5, color=primary_color, spaceBefore=3, spaceAfter=8))

    # 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), 4),
        ('BOX', (0,0), (-1,-1), 0.5, colors.HexColor("#CBD5E0")),
        ('VALIGN', (0,0), (-1,-1), 'MIDDLE'),
    ]))
    story.append(info_table)
    story.append(Spacer(1, 8))

    # Section 1: Declaração de Missão e Casos de Uso (CONOPS)
    story.append(Paragraph("1. Declaração da Missão e Casos de Uso (CONOPS)", h1_style))
    
    mission_text = (
        "<b>Declaração da Missão:</b> Projetar e construir um catamarã a vela de 45 pés para realizar com total segurança, "
        "autonomia e conforto a travessia oceânica de longo curso entre Vera Cruz (Bahia, Brasil) e a África do Sul "
        "(Cape Town ➔ Port Elizabeth ➔ Jeffreys Bay), servindo subsequentemente como plataforma de moradia a bordo "
        "(<i>liveaboard</i>) e expedição para 3 pessoas e 2 cães."
    )
    mission_table = Table([[Paragraph(mission_text, callout_style)]], colWidths=[170*mm])
    mission_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), 5),
    ]))
    story.append(mission_table)
    story.append(Spacer(1, 6))

    story.append(Paragraph("<b>Caso de Uso 1 (Primário): Travessia Oceânica de Longo Curso (Passagemaker)</b>", h2_style))
    story.append(Paragraph("• <b>Ambiente:</b> 20 a 35 dias de mar contínuo no Atlântico Sul, ventos de 15 a 45+ nós e ondas de 2,5 a 6,0 m.", bullet_style))
    story.append(Paragraph("• <b>Funções Exigidas:</b> Condução por 1 pessoa de vigia (<i>short-handed</i>), manobras de rizo 100% no cockpit protegido, geração autônoma de energia (solar + baterias LiFePO4) e dessalinização de água contínua.", bullet_style))

    story.append(Paragraph("<b>Caso de Uso 2: Navegação Costeira Difícil (África do Sul / Corrente das Agulhas)</b>", h2_style))
    story.append(Paragraph("• <b>Ambiente:</b> Tiros costeiros de 50 a 200 MN entre portos de abrigo sob forte correnteza (3-5 nós) e frentes frias de SW.", bullet_style))
    story.append(Paragraph("• <b>Funções Exigidas:</b> Potência auxiliar dupla (2x 45 hp) para entrada segura em barras e portos, aliada a alta rigidez estrutural.", bullet_style))

    story.append(Paragraph("<b>Caso de Uso 3: Moradia a Bordo e Ancoragem Prolongada (Liveaboard)</b>", h2_style))
    story.append(Paragraph("• <b>Ambiente:</b> Semanas fundeado em baías e enseadas com 3 tripulantes e 2 cachorros.", bullet_style))
    story.append(Paragraph("• <b>Funções Exigidas:</b> Ventilação cruzada natural, cockpit e salão em nível único (<i>single-level</i>), rede perimétrica de segurança para os cães e acesso fácil ao bote de apoio (<i>dinghy</i>).", bullet_style))

    story.append(Paragraph("<b>Caso de Uso 4: Encalhe Controlado na Maré e Manutenção Autônoma (Tidal Beaching)</b>", h2_style))
    story.append(Paragraph("• <b>Ambiente:</b> Encalhe na maré baixa para inspeção ou limpeza de fundo em locais sem travel-lift.", bullet_style))
    story.append(Paragraph("• <b>Funções Exigidas:</b> As duas quilhas rasas fixas (<i>minikeels</i>) suportam o peso total do barco assentado sobre a areia.", bullet_style))

    story.append(Spacer(1, 8))

    # Section 2: Áreas de Navegação e Enquadramento
    story.append(Paragraph("2. Áreas de Navegação e Enquadramento Normativo", h1_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)", table_cell_style),
            Paragraph("Cat. C / D", table_cell_style),
            Paragraph("Águas abrigadas; calado seguro na saída de Itaparica.", 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("Comunicação VHF 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, Dessalinizador e Linhas de Vida.", 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("Monitoramento do vento de SW contra a Corrente das Agulhas.", table_cell_style)
        ],
    ]
    nav_table = Table(nav_table_data, colWidths=[38*mm, 42*mm, 24*mm, 66*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), 3.5),
    ]))
    story.append(nav_table)

    story.append(PageBreak())

    # Section 3: Climatologia e Estratégia de Rota
    story.append(Paragraph("3. Climatologia e Estratégia de Rota", h1_style))
    story.append(Paragraph(
        "<b>Janela Ideal de Partida:</b> <b>Novembro a Fevereiro/Março (Verão do Hemisfério Sul)</b>. "
        "Permite contornar a Alta de Santa Helena pelo sul com frentes polares atenuadas.", body_style
    ))
    story.append(Paragraph("• <b>Trecho 1 (Vera Cruz ➔ Cape Town - ~3.600 MN):</b> Descer para SSE até ~26°S com os alísios de E/NE; curvar para leste entre 32°S e 35°S na esteira dos ventos de Oeste (<i>Westerlies</i>); subir para Cape Town apoiado pela Corrente de Benguela. Tempo estimado: 20 a 25 dias (6,5 a 7,5 nós).", bullet_style))
    story.append(Paragraph("• <b>Trecho 2 (Cape Town ➔ Jeffreys Bay - ~450 MN):</b> Navegar exclusivamente em janelas de 24h a 48h de vento fraco/favorável, mantendo-se na plataforma interna costeira para evitar o núcleo violento da Corrente das Agulhas contra ventos de SW.", bullet_style))

    story.append(Spacer(1, 6))

    # Section 4: Especificações Técnicas Preliminares
    story.append(Paragraph("4. Especificações Técnicas Preliminares do Catamarã 45'", h1_style))
    spec_data = [
        [Paragraph("Parâmetro", table_header_style), Paragraph("Dimensão / Especificação", table_header_style), Paragraph("Justificativa de Engenharia", table_header_style)],
        [Paragraph("Comprimento Total (LOA)", table_cell_bold), Paragraph("13,72 m (45,0 ft)", table_cell_style), Paragraph("Porte ideal para 3 pessoas e 2 cães com autonomia oceânica.", table_cell_style)],
        [Paragraph("Linha d'Água (LWL)", table_cell_bold), Paragraph("13,20 m", table_cell_style), Paragraph("Excelente relação LWL/LOA para alta 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("Elevado momento restaurador por estabilidade de forma.", table_cell_style)],
        [Paragraph("Calado (Draft)", table_cell_bold), Paragraph("1,25 m", table_cell_style), Paragraph("Quilhas rasas fixas de sacrifício; proteção de eixos e lemes.", table_cell_style)],
        [Paragraph("Vão Central (Clearance)", table_cell_bold), Paragraph("≥ 0,85 m", table_cell_style), Paragraph("Evita o impacto violento de ondas (slamming) no fundo da cabine.", table_cell_style)],
        [Paragraph("Deslocamento Máximo", table_cell_bold), Paragraph("13.800 kg (Payload: 3.800 kg)", table_cell_style), Paragraph("Capacidade para 35+ dias de mantimentos, diesel e água.", table_cell_style)],
        [Paragraph("Motorização Auxiliar", table_cell_bold), Paragraph("2 x 45 hp Diesel (Saildrive)", table_cell_style), Paragraph("Redundância e autonomia a motor de ~500 MN a 6 nós.", table_cell_style)],
        [Paragraph("Energia e Água", table_cell_bold), Paragraph("Solar 1.500Wp + LiFePO4 + Dessal.", table_cell_style), Paragraph("Autossuficiência elétrica e hídrica sem gerador a diesel.", table_cell_style)]
    ]
    spec_table = Table(spec_data, colWidths=[42*mm, 48*mm, 80*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), 3.5),
    ]))
    story.append(spec_table)

    story.append(Spacer(1, 8))

    # Section 5: Esboço Técnico do Barco
    story.append(Paragraph("5. Esboço Técnico Preliminar (Perfil e Arranjo Geral)", h1_style))
    esboco_path = '/home/magdalena/eee/alunos/rodolfo-g-giordano/esboco_catamara_45_rodolfo.png'
    if os.path.exists(esboco_path):
        # A4 width = 210mm, margins = 40mm -> available = 170mm (~480pt)
        img = Image(esboco_path, width=170*mm, height=128*mm)
        story.append(img)

    doc.build(story, canvasmaker=NumberedCanvas)

if __name__ == '__main__':
    output_pdf = '/home/magdalena/eee/alunos/rodolfo-g-giordano/Projeto_Catamara_45_Rodolfo_Giordano_Completo.pdf'
    build_complete_pdf(output_pdf)
    print(f"PDF completo gerado em: {output_pdf}")
