import json
from pathlib import Path
from reportlab.lib.pagesizes import letter
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

pdf_path = "/home/magdalena/eee/alunos/victor-lei/Dimensoes_Principais_Victor_Lei.pdf"

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_page_elements(num_pages)
            super().showPage()
        super().save()

    def draw_page_elements(self, page_count):
        self.saveState()
        self.setFont("Helvetica", 8)
        self.setFillColor(colors.HexColor("#718096"))
        
        # Header (página 2+)
        if self._pageNumber > 1:
            self.drawString(54, 750, "BRANA PROJETOS NAVAIS — ESPECIFICAÇÃO DE DIMENSÕES PRINCIPAIS")
            self.drawRightString(612 - 54, 750, "PROJETISTA: VICTOR LEI")
            self.setStrokeColor(colors.HexColor("#E2E8F0"))
            self.setLineWidth(0.5)
            self.line(54, 742, 612 - 54, 742)
        
        # Footer
        self.setStrokeColor(colors.HexColor("#CBD5E0"))
        self.setLineWidth(0.5)
        self.line(54, 45, 612 - 54, 45)
        self.drawString(54, 32, "Brana · Escola de Arquitetura e Engenharia Naval | Estaleiro Escola Embrião (EEE)")
        self.drawRightString(612 - 54, 32, f"Página {self._pageNumber} de {page_count}")
        self.restoreState()

doc = SimpleDocTemplate(
    pdf_path,
    pagesize=letter,
    leftMargin=54,
    rightMargin=54,
    topMargin=54,
    bottomMargin=54
)

styles = getSampleStyleSheet()

cor_primaria = colors.HexColor("#1A365D")   # Azul Marinho Brana
cor_secundaria = colors.HexColor("#2B6CB0") # Azul Médio
cor_fundo_tabela = colors.HexColor("#F7FAFC")
cor_borda = colors.HexColor("#CBD5E0")
cor_destaque = colors.HexColor("#2C5282")

style_titulo = ParagraphStyle(
    'DocTitle',
    parent=styles['Normal'],
    fontName='Helvetica-Bold',
    fontSize=20,
    leading=24,
    textColor=cor_primaria,
    spaceAfter=4
)

style_subtitulo = ParagraphStyle(
    'DocSubTitle',
    parent=styles['Normal'],
    fontName='Helvetica-Bold',
    fontSize=11,
    leading=14,
    textColor=cor_secundaria,
    spaceAfter=14
)

style_secao_titulo = ParagraphStyle(
    'SectionHeading',
    parent=styles['Normal'],
    fontName='Helvetica-Bold',
    fontSize=11,
    leading=14,
    textColor=colors.white,
    spaceBefore=0,
    spaceAfter=0
)

style_corpo = ParagraphStyle(
    'BodyDark',
    parent=styles['Normal'],
    fontName='Helvetica',
    fontSize=8.5,
    leading=12,
    textColor=colors.HexColor("#2D3748")
)

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

style_td = ParagraphStyle(
    'TableCell',
    parent=styles['Normal'],
    fontName='Helvetica',
    fontSize=8,
    leading=11,
    textColor=colors.HexColor("#2D3748"),
    alignment=1
)

style_td_label = ParagraphStyle(
    'TableCellLabel',
    parent=styles['Normal'],
    fontName='Helvetica-Bold',
    fontSize=8,
    leading=11,
    textColor=cor_primaria,
    alignment=0
)

story = []

# Título Principal
story.append(Paragraph("QUADRO DE DIMENSÕES & ESPECIFICAÇÃO TÉCNICA", style_titulo))
story.append(Paragraph("Projeto: Lancha Clássica 16 Pés &nbsp;|&nbsp; Projetista: <b>Victor Lei</b> &nbsp;|&nbsp; Data: 16/09/2026", style_subtitulo))

# Card de Apresentação
card_intro = [
    [Paragraph("<b>Definição da Embarcação:</b> Lancha cabinada de pequeno porte (estilo <i>cuddy cabin / runabout</i> clássico inspirado nas décadas de 60/70), casco quinado em 'V' moderado (<i>hard chine</i>), construída em compensado naval e resina epóxi, para navegação em represas e águas costeiras abrigadas.", style_corpo)]
]
t_intro = Table(card_intro, colWidths=[504])
t_intro.setStyle(TableStyle([
    ('BACKGROUND', (0,0), (-1,-1), colors.HexColor("#EDF2F7")),
    ('BOX', (0,0), (-1,-1), 1, colors.HexColor("#CBD5E0")),
    ('TOPPADDING', (0,0), (-1,-1), 6),
    ('BOTTOMPADDING', (0,0), (-1,-1), 6),
    ('LEFTPADDING', (0,0), (-1,-1), 8),
    ('RIGHTPADDING', (0,0), (-1,-1), 8),
]))
story.append(t_intro)
story.append(Spacer(1, 10))

# 1. Dimensões Principais do Casco
t_h1 = Table([[Paragraph("1. DIMENSÕES GEOMÉTRICAS PRINCIPAIS", style_secao_titulo)]], colWidths=[504])
t_h1.setStyle(TableStyle([
    ('BACKGROUND', (0,0), (-1,-1), cor_primaria),
    ('TOPPADDING', (0,0), (-1,-1), 4),
    ('BOTTOMPADDING', (0,0), (-1,-1), 4),
    ('LEFTPADDING', (0,0), (-1,-1), 8),
]))
story.append(t_h1)

dim_rows = [
    [Paragraph("Parâmetro", style_th), Paragraph("Símbolo", style_th), Paragraph("Valor (SI / Métrico)", style_th), Paragraph("Valor (Imperial)", style_th), Paragraph("Significado Prático no Projeto", style_th)],
    [Paragraph("Comprimento Total", style_td_label), Paragraph("LOA", style_td), Paragraph("<b>4,88 m</b>", style_td), Paragraph("16' 0\"", style_td), Paragraph("Comprimento total de proa a popa.", style_td_label)],
    [Paragraph("Comprimento na Linha d'Água", style_td_label), Paragraph("LWL", style_td), Paragraph("<b>4,42 m</b>", style_td), Paragraph("14' 6\"", style_td), Paragraph("Comprimento efetivo de flutuação.", style_td_label)],
    [Paragraph("Boca Máxima", style_td_label), Paragraph("BOA", style_td), Paragraph("<b>2,05 m</b>", style_td), Paragraph("6' 9\"", style_td), Paragraph("Largura total (ótima para carreta e garagem).", style_td_label)],
    [Paragraph("Boca na Linha d'Água", style_td_label), Paragraph("BWL", style_td), Paragraph("<b>1,75 m</b>", style_td), Paragraph("5' 9\"", style_td), Paragraph("Largura do casco no plano de flutuação.", style_td_label)],
    [Paragraph("Pontal Moldado", style_td_label), Paragraph("D", style_td), Paragraph("<b>0,88 m</b>", style_td), Paragraph("2' 11\"", style_td), Paragraph("Altura do fundo até a borda a meia-nau.", style_td_label)],
    [Paragraph("Borda Livre à Proa", style_td_label), Paragraph("FF", style_td), Paragraph("<b>0,95 m</b>", style_td), Paragraph("3' 1\"", style_td), Paragraph("Proa alta para cortar marola e manter o barco seco.", style_td_label)],
    [Paragraph("Borda Livre à Popa", style_td_label), Paragraph("FA", style_td), Paragraph("<b>0,55 m</b>", style_td), Paragraph("1' 10\"", style_td), Paragraph("Borda de popa com acesso fácil à água.", style_td_label)],
    [Paragraph("Calado do Casco (Projeto)", style_td_label), Paragraph("T", style_td), Paragraph("<b>0,28 m a 0,35 m</b>", style_td), Paragraph("11\" a 14\"", style_td), Paragraph("Permite aproximação em margens rasas e praias.", style_td_label)],
    [Paragraph("Calado com Motor Baixado", style_td_label), Paragraph("Tmax", style_td), Paragraph("<b>0,55 m a 0,60 m</b>", style_td), Paragraph("22\" a 24\"", style_td), Paragraph("Calado total operacional em navegação.", style_td_label)],
    [Paragraph("Ângulo de V na Popa", style_td_label), Paragraph("Deadrise AP", style_td), Paragraph("<b>17,72°</b>", style_td), Paragraph("17,72°", style_td), Paragraph("V moderado no espelho de popa.", style_td_label)],
    [Paragraph("Ângulo de V a Meia-Nau", style_td_label), Paragraph("Deadrise MP", style_td), Paragraph("<b>13,81° a 14,66°</b>", style_td), Paragraph("14°", style_td), Paragraph("Sustentação dinâmica e planeio suave.", style_td_label)],
    [Paragraph("Razão Comprimento / Boca", style_td_label), Paragraph("LOA / BOA", style_td), Paragraph("<b>2,38</b>", style_td), Paragraph("2,38", style_td), Paragraph("Elevada estabilidade transversal e espaço interno.", style_td_label)]
]

t_dim = Table(dim_rows, colWidths=[110, 44, 90, 60, 200])
t_dim.setStyle(TableStyle([
    ('BACKGROUND', (0,0), (-1,0), cor_destaque),
    ('GRID', (0,0), (-1,-1), 0.5, cor_borda),
    ('VALIGN', (0,0), (-1,-1), 'MIDDLE'),
    ('TOPPADDING', (0,0), (-1,-1), 3),
    ('BOTTOMPADDING', (0,0), (-1,-1), 3),
    ('ROWBACKGROUNDS', (0,1), (-1,-1), [colors.white, cor_fundo_tabela])
]))
story.append(t_dim)
story.append(Spacer(1, 10))

# 2. Coeficientes Hidrostáticos
t_h2 = Table([[Paragraph("2. COEFICIENTES HIDROSTÁTICOS & FORMA DE CARENA", style_secao_titulo)]], colWidths=[504])
t_h2.setStyle(TableStyle([
    ('BACKGROUND', (0,0), (-1,-1), cor_primaria),
    ('TOPPADDING', (0,0), (-1,-1), 4),
    ('BOTTOMPADDING', (0,0), (-1,-1), 4),
    ('LEFTPADDING', (0,0), (-1,-1), 8),
]))
story.append(t_h2)

coef_rows = [
    [Paragraph("Coeficiente / Propriedade", style_th), Paragraph("Símbolo", style_th), Paragraph("Valor Calculado", style_th), Paragraph("Interpretação e Relevância Técnica", style_th)],
    [Paragraph("Coeficiente de Bloco", style_td_label), Paragraph("Cb", style_td), Paragraph("<b>0,568</b>", style_td), Paragraph("Relação do volume submerso com o paralelepípedo circunscrito.", style_td_label)],
    [Paragraph("Coeficiente de Seção Mestra", style_td_label), Paragraph("Cm", style_td), Paragraph("<b>0,686</b>", style_td), Paragraph("Fator de preenchimento da baliza mestra em V com chine.", style_td_label)],
    [Paragraph("Coeficiente Prismático", style_td_label), Paragraph("Cp", style_td), Paragraph("<b>0,828 (0,60 a pleno)</b>", style_td), Paragraph("Distribuição longitudinal de volume (popa cheia para sustentação).", style_td_label)],
    [Paragraph("Área da Seção Mestra", style_td_label), Paragraph("Am (Amax)", style_td), Paragraph("<b>0,419 m²</b>", style_td), Paragraph("Área submersa na baliza 4 a calado de referência.", style_td_label)],
    [Paragraph("Volume de Carena", style_td_label), Paragraph("∇ (nabla)", style_td), Paragraph("<b>1,53 m³ (máx)</b>", style_td), Paragraph("Volume total submerso integrado da carena.", style_td_label)]
]

t_coef = Table(coef_rows, colWidths=[140, 50, 94, 220])
t_coef.setStyle(TableStyle([
    ('BACKGROUND', (0,0), (-1,0), cor_destaque),
    ('GRID', (0,0), (-1,-1), 0.5, cor_borda),
    ('VALIGN', (0,0), (-1,-1), 'MIDDLE'),
    ('TOPPADDING', (0,0), (-1,-1), 3),
    ('BOTTOMPADDING', (0,0), (-1,-1), 3),
    ('ROWBACKGROUNDS', (0,1), (-1,-1), [colors.white, cor_fundo_tabela])
]))
story.append(t_coef)
story.append(Spacer(1, 10))

# 3. Estimativa de Pesos, Lotação e Propulsão
t_h3 = Table([[Paragraph("3. ESTIMATIVA DE PESOS, LOTAÇÃO E PROPULSÃO RECOMENDADA", style_secao_titulo)]], colWidths=[504])
t_h3.setStyle(TableStyle([
    ('BACKGROUND', (0,0), (-1,-1), cor_primaria),
    ('TOPPADDING', (0,0), (-1,-1), 4),
    ('BOTTOMPADDING', (0,0), (-1,-1), 4),
    ('LEFTPADDING', (0,0), (-1,-1), 8),
]))
story.append(t_h3)

pesos_rows = [
    [Paragraph("Item", style_th), Paragraph("Valor / Faixa", style_th), Paragraph("Item", style_th), Paragraph("Valor / Faixa", style_th)],
    [Paragraph("Peso Leve (Casco + Convés)", style_td_label), Paragraph("~305 kg", style_td), Paragraph("Motor de Popa (50-60 HP)", style_td_label), Paragraph("~115 kg", style_td)],
    [Paragraph("Sistemas + Equipamentos", style_td_label), Paragraph("~100 kg", style_td), Paragraph("<b>Peso Leve Pronto (Lightship)</b>", style_td_label), Paragraph("<b>~520 kg</b>", style_td)],
    [Paragraph("Combustível (Gasolina 50L)", style_td_label), Paragraph("~38 kg", style_td), Paragraph("Água Doce (Ducha 25L)", style_td_label), Paragraph("~25 kg", style_td)],
    [Paragraph("Lotação Máxima Diurna", style_td_label), Paragraph("6 pessoas (~450 kg)", style_td), Paragraph("Acomodações Pernoite", style_td_label), Paragraph("2 adultos (cama em V)", style_td)],
    [Paragraph("<b>Deslocamento Total em Carga</b>", style_td_label), Paragraph("<b>~1.068 kg</b>", style_td), Paragraph("Velocidade de Cruzeiro / Top", style_td_label), Paragraph("20-23 nós / 30-33 nós", style_td)],
]

t_pesos = Table(pesos_rows, colWidths=[140, 112, 140, 112])
t_pesos.setStyle(TableStyle([
    ('BACKGROUND', (0,0), (-1,0), cor_destaque),
    ('GRID', (0,0), (-1,-1), 0.5, cor_borda),
    ('VALIGN', (0,0), (-1,-1), 'MIDDLE'),
    ('TOPPADDING', (0,0), (-1,-1), 3),
    ('BOTTOMPADDING', (0,0), (-1,-1), 3),
    ('ROWBACKGROUNDS', (0,1), (-1,-1), [colors.white, cor_fundo_tabela])
]))
story.append(t_pesos)

doc.build(story, canvasmaker=NumberedCanvas)
print("PDF de Dimensões Principais gerado com sucesso!")
