from reportlab.lib.pagesizes import letter
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib import colors
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, HRFlowable
from reportlab.pdfgen import canvas

pdf_path = "/home/magdalena/eee/alunos/caliandra/Coeficientes_Hidrostaticos_e_Forma_Caliandra.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_number(num_pages)
            canvas.Canvas.showPage(self)
        canvas.Canvas.save(self)

    def draw_page_number(self, page_count):
        self.saveState()
        self.setFont("Helvetica", 8)
        self.setFillColor(colors.HexColor("#5A626B"))
        # Header
        self.drawString(54, 750, "BRANA · Escola de Arquitetura e Engenharia Naval | Estaleiro Escola Embrião")
        self.drawRightString(612 - 54, 750, "Hidrostática e Coeficientes de Carena — O RESGATE")
        self.setStrokeColor(colors.HexColor("#D3D9DC"))
        self.setLineWidth(0.5)
        self.line(54, 742, 612 - 54, 742)
        
        # Footer
        self.line(54, 45, 612 - 54, 45)
        self.drawString(54, 32, "Embarcação: O RESGATE (SAR 9.0m) · Projetista: Caliandra")
        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=60,
    bottomMargin=60
)

styles = getSampleStyleSheet()

title_style = ParagraphStyle(
    "DocTitle",
    parent=styles["Normal"],
    fontName="Helvetica-Bold",
    fontSize=16,
    leading=20,
    textColor=colors.HexColor("#1F2429"),
    spaceAfter=4
)

subtitle_style = ParagraphStyle(
    "DocSubtitle",
    parent=styles["Normal"],
    fontName="Helvetica",
    fontSize=9.5,
    leading=13,
    textColor=colors.HexColor("#5A626B"),
    spaceAfter=10
)

sec_title_style = ParagraphStyle(
    "SecTitle",
    parent=styles["Normal"],
    fontName="Helvetica-Bold",
    fontSize=10.5,
    leading=14,
    textColor=colors.HexColor("#C4262E"),
    spaceBefore=8,
    spaceAfter=3
)

p_style = ParagraphStyle(
    "Para",
    parent=styles["Normal"],
    fontName="Helvetica",
    fontSize=8.5,
    leading=11.5,
    textColor=colors.HexColor("#333333"),
    spaceAfter=4
)

th_style = ParagraphStyle(
    "TH",
    parent=styles["Normal"],
    fontName="Helvetica-Bold",
    fontSize=7.5,
    leading=9.5,
    textColor=colors.white,
    alignment=1
)

td_style = ParagraphStyle(
    "TD",
    parent=styles["Normal"],
    fontName="Helvetica",
    fontSize=7.5,
    leading=9.5,
    textColor=colors.HexColor("#1F2429"),
    alignment=1
)

td_left = ParagraphStyle(
    "TDLeft",
    parent=styles["Normal"],
    fontName="Helvetica-Bold",
    fontSize=7.5,
    leading=9.5,
    textColor=colors.HexColor("#1F2429")
)

story = []

# Title & Subtitle
story.append(Paragraph("Relatório de Coeficientes Hidrostáticos e Forma de Carena", title_style))
story.append(Paragraph("<b>Projeto:</b> O RESGATE (Lancha SAR 9.0m Deep-V) | <b>Projetista:</b> Caliandra | <b>Escola:</b> BRANA", subtitle_style))

# Intro Box
intro_p = (
    "<b>Definição Teórica:</b> Os coeficientes de forma de carena são grandezas adimensionais que comparam o volume e as áreas "
    "reais da parte submersa do casco com sólidos geométricos fundamentais (prismas retangulares e cilindros circunscritos). "
    "Eles ditam a resistência ao avanço, a sustentação hidrodinâmica em planeio, a distribuição longitudinal de empuxo e a estabilidade da embarcação."
)
intro_tab = Table([[Paragraph(intro_p, p_style)]], colWidths=[504])
intro_tab.setStyle(TableStyle([
    ("BACKGROUND", (0, 0), (-1, -1), colors.HexColor("#EFF2F3")),
    ("PADDING", (0, 0), (-1, -1), 6),
    ("BOX", (0, 0), (-1, -1), 0.5, colors.HexColor("#D3D9DC")),
    ("ROUNDEDCORNERS", [4, 4, 4, 4])
]))
story.append(intro_tab)
story.append(Spacer(1, 4))

# 1. Coeficientes Adimensionais de Forma
story.append(Paragraph("1. Coeficientes de Forma da Carena (Condição de Projeto: DWL = 0,61 m)", sec_title_style))
story.append(HRFlowable(width="100%", thickness=0.5, color=colors.HexColor("#C4262E"), spaceAfter=4, spaceBefore=0))

coef_data = [
    [Paragraph("Coeficiente de Forma", th_style), Paragraph("Símbolo", th_style), Paragraph("Fórmula Matemática", th_style), Paragraph("Valor", th_style), Paragraph("Significado Físico / Aplicação Naval", th_style)],
    [Paragraph("Coeficiente de Bloco", td_left), Paragraph("Cb", td_style), Paragraph("&nabla; / (LWL &times; BWL &times; Tc)", td_style), Paragraph("<b>0,445</b>", td_style), Paragraph("Esbeltez da carena; valor baixo típico de cascos rápidos em V profundo para corte de ondas sem impactos secos.", td_style)],
    [Paragraph("Coeficiente de Seção Mestra", td_left), Paragraph("Cm", td_style), Paragraph("Am / (BWL &times; Tc)", td_style), Paragraph("<b>0,689</b>", td_style), Paragraph("Plenitude da baliza mestra; reflete o fundo em V com deadrise de 15,3° e quinas vivas bem marcadas.", td_style)],
    [Paragraph("Coeficiente Prismático Longitudinal", td_left), Paragraph("Cp", td_style), Paragraph("&nabla; / (LWL &times; Am) = Cb / Cm", td_style), Paragraph("<b>0,646</b>", td_style), Paragraph("Distribuição de volume longitudinal; faixa ideal (0,62 a 0,68) para transição ao planeio e altas velocidades (>30 nós).", td_style)],
    [Paragraph("Coeficiente de Linha d'Água", td_left), Paragraph("Cw (ou Cwp)", td_style), Paragraph("Awp / (LWL &times; BWL)", td_style), Paragraph("<b>0,854</b>", td_style), Paragraph("Plenitude do plano de flutuação; valor elevado garante alta inércia de área e excelente estabilidade inicial (GM).", td_style)],
    [Paragraph("Coeficiente Prismático Vertical", td_left), Paragraph("Cpv", td_style), Paragraph("&nabla; / (Awp &times; Tc)", td_style), Paragraph("<b>0,521</b>", td_style), Paragraph("Distribuição de volume na vertical; define a posição relativa do Centro Vertical de Carena (KB).", td_style)],
    [Paragraph("Razão Deslocamento-Comprimento", td_left), Paragraph("DLR", td_style), Paragraph("[&Delta; (lbs) / 2240] / [LWL (ft) / 100]&sup3;", td_style), Paragraph("<b>371,0</b>", td_style), Paragraph("Robusto para embarcação profissional SAR em plena carga operacional com capacidade para 8 pessoas.", td_style)]
]

t_coef = Table(coef_data, colWidths=[120, 45, 125, 45, 169])
t_coef.setStyle(TableStyle([
    ("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#1F2429")),
    ("GRID", (0, 0), (-1, -1), 0.5, colors.HexColor("#CBD5E1")),
    ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
    ("TOPPADDING", (0, 0), (-1, -1), 2.2),
    ("BOTTOMPADDING", (0, 0), (-1, -1), 2.2),
    ("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.HexColor("#FFFFFF"), colors.HexColor("#F8FAFC")])
]))
story.append(t_coef)
story.append(Spacer(1, 4))

# 2. Tabela de Variação Hidrostática com o Calado
story.append(Paragraph("2. Propriedades Hidrostáticas em Função do Calado (Água Salgada &rho; = 1.025 kg/m³)", sec_title_style))
story.append(HRFlowable(width="100%", thickness=0.5, color=colors.HexColor("#C4262E"), spaceAfter=4, spaceBefore=0))

hidro_tabela = [
    [Paragraph("Calado (m)", th_style), Paragraph("Desloc. (&Delta; kg)", th_style), Paragraph("Volume (&nabla; m³)", th_style), Paragraph("LWL (m)", th_style), Paragraph("BWL (m)", th_style), Paragraph("Cb", th_style), Paragraph("Cm", th_style), Paragraph("Cp", th_style), Paragraph("Condição Típica", th_style)],
    [Paragraph("0,45 m", td_style), Paragraph("2.981 kg", td_style), Paragraph("2,908 m³", td_style), Paragraph("6,73 m", td_style), Paragraph("2,38 m", td_style), Paragraph("0,399", td_style), Paragraph("0,632", td_style), Paragraph("0,631", td_style), Paragraph("Casco Leve em Lastro", td_left)],
    [Paragraph("0,50 m", td_style), Paragraph("3.652 kg", td_style), Paragraph("3,563 m³", td_style), Paragraph("6,95 m", td_style), Paragraph("2,44 m", td_style), Paragraph("0,417", td_style), Paragraph("0,655", td_style), Paragraph("0,637", td_style), Paragraph("Lightship Operacional", td_left)],
    [Paragraph("0,52 m", td_style), Paragraph("3.931 kg", td_style), Paragraph("3,835 m³", td_style), Paragraph("7,02 m", td_style), Paragraph("2,46 m", td_style), Paragraph("0,424", td_style), Paragraph("0,663", td_style), Paragraph("0,640", td_style), Paragraph("Prontidão (4 trip + 30% comb)", td_left)],
    [Paragraph("0,55 m", td_style), Paragraph("4.362 kg", td_style), Paragraph("4,256 m³", td_style), Paragraph("7,16 m", td_style), Paragraph("2,49 m", td_style), Paragraph("0,431", td_style), Paragraph("0,673", td_style), Paragraph("0,640", td_style), Paragraph("Missão Padrão (4 trip + 100%)", td_left)],
    [Paragraph("<b>0,61 m</b>", td_style), Paragraph("<b>5.262 kg</b>", td_style), Paragraph("<b>5,134 m³</b>", td_style), Paragraph("<b>7,36 m</b>", td_style), Paragraph("<b>2,55 m</b>", td_style), Paragraph("<b>0,445</b>", td_style), Paragraph("<b>0,689</b>", td_style), Paragraph("<b>0,646</b>", td_style), Paragraph("<b>PLENA CARGA (PROJETO)</b>", td_left)],
    [Paragraph("0,65 m", td_style), Paragraph("5.890 kg", td_style), Paragraph("5,746 m³", td_style), Paragraph("7,51 m", td_style), Paragraph("2,59 m", td_style), Paragraph("0,451", td_style), Paragraph("0,697", td_style), Paragraph("0,647", td_style), Paragraph("Sobrecarga Máxima SAR", td_left)]
]

t_hidro = Table(hidro_tabela, colWidths=[52, 60, 60, 48, 48, 40, 40, 40, 116])
t_hidro.setStyle(TableStyle([
    ("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#1F2429")),
    ("BACKGROUND", (0, 5), (-1, 5), colors.HexColor("#E0F2FE")), # Linha de Projeto
    ("GRID", (0, 0), (-1, -1), 0.5, colors.HexColor("#CBD5E1")),
    ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
    ("TOPPADDING", (0, 0), (-1, -1), 2.0),
    ("BOTTOMPADDING", (0, 0), (-1, -1), 2.0),
    ("ROWBACKGROUNDS", (0, 1), (0, 4), [colors.HexColor("#FFFFFF"), colors.HexColor("#F8FAFC")]),
    ("ROWBACKGROUNDS", (0, 6), (-1, -1), [colors.HexColor("#FFFFFF"), colors.HexColor("#F8FAFC")])
]))
story.append(t_hidro)
story.append(Spacer(1, 4))

# 3. Centros de Carena e Parâmetros de Estabilidade
story.append(Paragraph("3. Centros de Flutuação e Parâmetros de Estabilidade Inicial", sec_title_style))
story.append(HRFlowable(width="100%", thickness=0.5, color=colors.HexColor("#C4262E"), spaceAfter=4, spaceBefore=0))

centros_p = (
    "• <b>Centro Longitudinal de Carena (LCB):</b> <b>3,38 m a vante do Espelho</b> (~46,0% de LWL a partir do espelho), perfeitamente alinhado com o LCG para garantir navegação com atitude de planeio nivelada (trim ótimo entre 3° e 4°).<br/>"
    "• <b>Centro de Flutuação da Linha d'Água (LCF):</b> <b>3,35 m a vante do Espelho</b>.<br/>"
    "• <b>Centro Vertical de Carena (KB):</b> <b>0,36 m acima da Linha de Base</b> (~59% do calado Tc).<br/>"
    "• <b>Raio Metacêntrico Transversal (BMt):</b> <b>~1,18 m</b> (derivado da inércia transversal da linha d'água: It / &nabla;).<br/>"
    "• <b>Altura Metacêntrica Transversal Estimada (GMt):</b> <b>~0,85 m</b> (garante excelente estabilidade estática e rápida recuperação em manobras e resgates sem adernamento excessivo)."
)

centros_tab = Table([[Paragraph(centros_p, p_style)]], colWidths=[504])
centros_tab.setStyle(TableStyle([
    ("BACKGROUND", (0, 0), (-1, -1), colors.HexColor("#F0FDF4")),
    ("PADDING", (0, 0), (-1, -1), 6),
    ("BOX", (0, 0), (-1, -1), 0.5, colors.HexColor("#BBF7D0")),
    ("ROUNDEDCORNERS", [4, 4, 4, 4])
]))
story.append(centros_tab)

doc.build(story, canvasmaker=NumberedCanvas)
print("PDF dos Coeficientes Hidrostaticos gerado com sucesso em:", pdf_path)
