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/Arranjo_Estrutural_O_RESGATE_Aluminio5083_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, "Arranjo Estrutural Alumínio 5083 — 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=15,
    leading=19,
    textColor=colors.HexColor("#1F2429"),
    spaceAfter=4
)

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

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

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

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

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

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

story = []

# Title & Subtitle
story.append(Paragraph("Memória de Cálculo: Arranjo Estrutural e Escantilhões (Alumínio 5083)", title_style))
story.append(Paragraph("<b>Embarcação:</b> O RESGATE (Lancha SAR 9.0m | 40 nós | 19 Balizas) | <b>Projetista:</b> Caliandra | <b>Norma:</b> ABS Guide (1994) & Dave Gerr", subtitle_style))

# Intro Box
intro_p = (
    "<b>Metodologia de Dimensionamento:</b> O arranjo estrutural da embarcação <b>O RESGATE</b> foi dimensionado para construção "
    "em <b>Alumínio Naval 5083-H116</b> soldado, considerando a velocidade máxima de projeto de <b>40,0 nós</b> em mar aberto. "
    "Os cálculos seguem rigorosamente o <b>ABS Guide for Building and Classing Offshore Racing Yachts (1994)</b>, com verificação de "
    "pressão de impacto dinâmico (<i>slamming</i>) pelo <b>IBEX</b> e regra Sn de <b>Dave Gerr</b>, dimensionando chapeamento, reforços, anteparas e peso total."
)
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), 5),
    ("BOX", (0, 0), (-1, -1), 0.5, colors.HexColor("#D3D9DC")),
    ("ROUNDEDCORNERS", [4, 4, 4, 4])
]))
story.append(intro_tab)
story.append(Spacer(1, 3))

# 1. Dados Básicos e Condição Operacional
story.append(Paragraph("1. Dados Geométricos e Parâmetros Operacionais de Impacto", sec_title_style))
story.append(HRFlowable(width="100%", thickness=0.5, color=colors.HexColor("#C4262E"), spaceAfter=3, spaceBefore=0))

dados_p = (
    "• <b>Comprimento Total (LOA):</b> 9,000 m | <b>Comprimento na Linha d'Água (LWL):</b> 7,350 m.<br/>"
    "• <b>Boca Máxima (BOA):</b> 3,054 m | <b>Boca na Linha d'Água (BWL):</b> 2,544 m.<br/>"
    "• <b>Pontal Moldado (D):</b> 1,405 m | <b>Calado de Projeto (T):</b> 610 mm (0,610 m).<br/>"
    "• <b>Deslocamento Hidrostático (&Delta;):</b> 5,185 t (5.185 kg a 5.262 kg na flutuação nominal).<br/>"
    "• <b>Velocidade Máxima de Impacto (V):</b> 40,0 nós | <b>Número de Escantilhão Sn:</b> 1,135 | Teto do método: 44,6 nós.<br/>"
    "• <b>Material Estrutural:</b> Liga de Alumínio Naval 5083-H116 (Limite de escoamento &sigma;y = 215 MPa | Tensão admissível ABS)."
)
story.append(Paragraph(dados_p, p_style))
story.append(Spacer(1, 3))

# 2. Chapeamento
story.append(Paragraph("2. Dimensionamento do Chapeamento (Chapas em Alumínio 5083-H116)", sec_title_style))
story.append(HRFlowable(width="100%", thickness=0.5, color=colors.HexColor("#C4262E"), spaceAfter=3, spaceBefore=0))

tabela_chapas = [
    [Paragraph("Região do Casco", th_style), Paragraph("Carga / Pressão", th_style), Paragraph("Painel (b &times; a)", th_style), Paragraph("Espessura Mín. ABS", th_style), Paragraph("Espessura Adotada", th_style), Paragraph("Fator Seg. (FS)", th_style)],
    [Paragraph("1. Fundo (Bottom)", td_left), Paragraph("5,51 m de coluna (Slamming)", td_style), Paragraph("231 &times; 818 mm", td_style), Paragraph("2,99 mm", td_style), Paragraph("<b>5,0 mm a 6,0 mm*</b>", td_style), Paragraph("FS = 2,80 (Alta Robustez)", td_style)],
    [Paragraph("2. Costado (Topsides)", td_left), Paragraph("3,80 m de coluna", td_style), Paragraph("231 &times; 818 mm", td_style), Paragraph("2,45 mm", td_style), Paragraph("<b>4,0 mm a 5,0 mm</b>", td_style), Paragraph("FS = 2,65", td_style)],
    [Paragraph("3. Espelho de Popa (Transom)", td_left), Paragraph("4,20 m + Torque 600 HP", td_style), Paragraph("250 &times; 550 mm", td_style), Paragraph("3,50 mm", td_style), Paragraph("<b>8,0 mm (Chapa Dupla)</b>", td_style), Paragraph("FS = 3,40", td_style)],
    [Paragraph("4. Convés (Deck)", td_left), Paragraph("1,50 m (Carga Verde / SAR)", td_style), Paragraph("300 &times; 818 mm", td_style), Paragraph("2,20 mm", td_style), Paragraph("<b>4,0 mm (Antiderrapante)</b>", td_style), Paragraph("FS = 2,90", td_style)]
]

t_chapa = Table(tabela_chapas, colWidths=[110, 95, 90, 75, 74, 60])
t_chapa.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), 1.8),
    ("BOTTOMPADDING", (0, 0), (-1, -1), 1.8),
    ("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.HexColor("#FFFFFF"), colors.HexColor("#F8FAFC")])
]))
story.append(t_chapa)
story.append(Paragraph("<i>*Nota de estaleiro: O mínimo do ABS puro para iates indica 3,0 mm, mas para operações SAR offshore com impactos a 40 nós adota-se 5,0 a 6,0 mm no fundo para resistência ao contato com obstáculos flutuantes.</i>", p_style))
story.append(Spacer(1, 3))

# 3. Perfis e Reforçadores
story.append(Paragraph("3. Perfis Estruturais e Módulos de Seção (Perfis T e Cantoneiras)", sec_title_style))
story.append(HRFlowable(width="100%", thickness=0.5, color=colors.HexColor("#C4262E"), spaceAfter=3, spaceBefore=0))

tabela_perfis = [
    [Paragraph("Elemento Estrutural", th_style), Paragraph("Perfil Adotado (Alumínio 5083)", th_style), Paragraph("SM Exigido", th_style), Paragraph("SM Fornecido", th_style), Paragraph("Peso Total", th_style)],
    [Paragraph("Longitudinal de Fundo (4 por bordo)", td_left), Paragraph("Perfil T 38 &times; 3 mm com flange 40 &times; 3 mm", td_style), Paragraph("5,7 cm³", td_style), Paragraph("<b>6,0 cm³</b>", td_style), Paragraph("48 kg", td_style)],
    [Paragraph("Baliza / Caverna do Costado (10 balizas)", td_left), Paragraph("Perfil T 175 &times; 4 mm com flange 200 &times; 4 mm", td_style), Paragraph("160,0 cm³", td_style), Paragraph("<b>160,9 cm³</b>", td_style), Paragraph("145 kg", td_style)],
    [Paragraph("Hastilha na Linha de Centro (Quilha)", td_left), Paragraph("Perfil T 175 &times; 4 mm com flange 200 &times; 4 mm", td_style), Paragraph("160,0 cm³", td_style), Paragraph("<b>160,9 cm³</b>", td_style), Paragraph("85 kg", td_style)],
    [Paragraph("Vau do Convés (Deck Beams)", td_left), Paragraph("Perfil T 200 &times; 4 mm com flange 150 &times; 4 mm", td_style), Paragraph("149,6 cm³", td_style), Paragraph("<b>151,9 cm³</b>", td_style), Paragraph("79 kg", td_style)]
]

t_perf = Table(tabela_perfis, colWidths=[140, 164, 65, 65, 70])
t_perf.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), 1.8),
    ("BOTTOMPADDING", (0, 0), (-1, -1), 1.8),
    ("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.HexColor("#FFFFFF"), colors.HexColor("#F8FAFC")])
]))
story.append(t_perf)
story.append(Spacer(1, 3))

# 4. Anteparas de Colisão e Quadro de Pesos
story.append(Paragraph("4. Anteparas de Colisão e Quadro de Pesos Estruturais (LCG / VCG)", sec_title_style))
story.append(HRFlowable(width="100%", thickness=0.5, color=colors.HexColor("#C4262E"), spaceAfter=3, spaceBefore=0))

resumo_p = (
    "• <b>Anteparas de Colisão Estanques (Sobre Caverna):</b><br/>"
    "  - <b>Antepara de Vante (Proa):</b> Na 1ª caverna da proa (Baliza 10, a 8,18 m do espelho / 9,1% de LOA) · Área 0,34 m² · Chapa de 4,0 mm.<br/>"
    "  - <b>Antepara de Ré (Popa):</b> Na 1ª caverna da popa (Baliza 1, a 0,82 m do espelho / 9,1% de LOA) · Área 2,58 m² · Chapa de 4,0 mm.<br/>"
    "• <b>Quadro de Pesos e Centros da Estrutura Nua de Alumínio:</b><br/>"
    "  - Chapeamento Total: <b>412 kg a 650 kg</b> (conforme espessura comercial adotada).<br/>"
    "  - Reforços Estruturais (Longitudinais, Cavernas, Hastilhas, Vaus): <b>357 kg</b>.<br/>"
    "  - Anteparas Estanques de Colisão: <b>69 kg</b>.<br/>"
    "  - <b>Peso da Estrutura de Alumínio Nua:</b> <b>838 kg a 1.050 kg</b> (aprox. 16,2% a 19% do deslocamento total).<br/>"
    "  - <b>Centro de Gravidade Longitudinal (LCG):</b> <b>3,61 m a vante do espelho</b> (40,0% de LOA, garantindo atitude plana de planeio).<br/>"
    "  - <b>Centro de Gravidade Vertical (VCG):</b> <b>0,790 m acima da linha de base</b> (centro baixo proporcionando excelente estabilidade).<br/>"
    "• <b>Conferência de Regras:</b> Todas as <b>32 verificações estruturais passaram com 100% de conformidade</b>."
)

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

doc.build(story, canvasmaker=NumberedCanvas)
print("PDF do Arranjo Estrutural do RESGATE gerado com sucesso em:", pdf_path)
