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_Lancha_488m_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, "Memória de Cálculo — Arranjo Estrutural (ABS / Gerr)")
        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, "Projeto: Lancha 4,88m Quinada · 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 de Arranjo Estrutural e Escantilhões", title_style))
story.append(Paragraph("<b>Embarcação:</b> Lancha Quinada 4,88 m (Calado 300 mm | Espelho 10°) | <b>Projetista:</b> Caliandra | <b>Norma:</b> ABS Guide (1994) & Dave Gerr", subtitle_style))

# Intro Box
intro_p = (
    "<b>Metodologia de Dimensionamento:</b> O dimensionamento estrutural foi executado utilizando o motor oficial da Brana "
    "(<i>brana-arranjo-estrutural</i>) a partir da tabela de cotas do casco quinado de 4,88 m (8 balizas). "
    "O cálculo segue os critérios do <b>ABS Guide for Building and Classing Offshore Racing Yachts (1994)</b>, conferido pela "
    "<b>regra Sn de Dave Gerr</b> e pela carga de impacto do <b>IBEX</b>, com calado fixado em <b>300 mm</b> e inclinação do espelho de popa em <b>10,0°</b>."
)
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 da Carena
story.append(Paragraph("1. Dados Geométricos e Hidrostáticos da Carena", sec_title_style))
story.append(HRFlowable(width="100%", thickness=0.5, color=colors.HexColor("#C4262E"), spaceAfter=3, spaceBefore=0))

carena_p = (
    "• <b>Comprimento Total (LOA):</b> 4,880 m | <b>Comprimento na Linha d'Água (LWL):</b> 4,311 m.<br/>"
    "• <b>Boca Máxima (BOA):</b> 2,050 m (localizada a 43% do espelho de popa) | <b>Boca na Linha d'Água (BWL):</b> 1,660 m.<br/>"
    "• <b>Pontal Moldado (D):</b> 0,880 m | <b>Calado de Projeto (T):</b> 300 mm (0,300 m — especificado).<br/>"
    "• <b>Espelho de Popa:</b> Inclinação de <b>10,0°</b> da vertical.<br/>"
    "• <b>Deslocamento Hidrostático (&Delta;):</b> <b>0,969 t (969 kg)</b> em água salgada (&rho; = 1.025 kg/m³).<br/>"
    "• <b>Número de Escantilhão Sn:</b> 0,265 | Teto de velocidade do método: 44,9 nós."
)
story.append(Paragraph(carena_p, p_style))
story.append(Spacer(1, 3))

# 2. Espessuras de Chapa
story.append(Paragraph("2. Dimensionamento do Chapeamento (Compensado Naval)", 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 Hidrostática", th_style), Paragraph("Painel (b &times; a)", th_style), Paragraph("Espessura Exigida", th_style), Paragraph("Espessura Adotada", th_style), Paragraph("Fator Seg. (FS)", th_style)],
    [Paragraph("1. Fundo (Bottom)", td_left), Paragraph("3,80 m de coluna", td_style), Paragraph("144 &times; 444 mm", td_style), Paragraph("6,70 mm (ABS)", td_style), Paragraph("<b>9,0 mm</b>", td_style), Paragraph("FS = 3,60", td_style)],
    [Paragraph("2. Costado (Topsides)", td_left), Paragraph("2,40 m de coluna", td_style), Paragraph("144 &times; 444 mm", td_style), Paragraph("5,50 mm (ABS)", td_style), Paragraph("<b>9,0 mm</b>", td_style), Paragraph("FS = 4,10", td_style)],
    [Paragraph("3. Espelho de Popa (Transom)", td_left), Paragraph("2,80 m de coluna", td_style), Paragraph("150 &times; 400 mm", td_style), Paragraph("4,80 mm (ABS)", td_style), Paragraph("<b>6,0 mm</b>", td_style), Paragraph("FS = 2,80", td_style)],
    [Paragraph("4. Convés (Deck)", td_left), Paragraph("1,20 m (carga verde)", td_style), Paragraph("200 &times; 444 mm", td_style), Paragraph("4,20 mm (ABS)", td_style), Paragraph("<b>6,0 mm</b>", td_style), Paragraph("FS = 3,10", td_style)]
]

t_chapa = Table(tabela_chapas, colWidths=[110, 85, 95, 80, 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(Spacer(1, 4))

# 3. Perfis e Reforçadores
story.append(Paragraph("3. Perfis e Módulos de Seção dos Reforçadores Estruturais", 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 Escolhido (Madeira / Comp.)", th_style), Paragraph("SM Exigido", th_style), Paragraph("SM Fornecido", th_style), Paragraph("Peso Total", th_style)],
    [Paragraph("Longitudinal do Fundo (5 por bordo)", td_left), Paragraph("Barra maciça de 19 &times; 38 mm", td_style), Paragraph("8,8 cm³", td_style), Paragraph("<b>10,3 cm³</b>", td_style), Paragraph("28 kg", td_style)],
    [Paragraph("Baliza / Caverna do Costado (10 balizas)", td_left), Paragraph("Alma 19 &times; 75 mm + Chapuz 40 &times; 19 mm", td_style), Paragraph("82,5 cm³", td_style), Paragraph("<b>85,0 cm³</b>", td_style), Paragraph("62 kg", td_style)],
    [Paragraph("Hastilha na Linha de Centro", td_left), Paragraph("Alma 19 &times; 100 mm + Chapuz 75 &times; 19 mm", td_style), Paragraph("181,8 cm³", td_style), Paragraph("<b>185,3 cm³</b>", td_style), Paragraph("44 kg", td_style)],
    [Paragraph("Vau do Convés", td_left), Paragraph("Alma 25 &times; 200 mm + Chapuz 100 &times; 25 mm", td_style), Paragraph("533,3 cm³", td_style), Paragraph("<b>572,2 cm³</b>", td_style), Paragraph("47 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, 4))

# 4. Anteparas de Colisão e Quadro de Pesos
story.append(Paragraph("4. Anteparas de Colisão e Quadro de Pesos e Centros (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:</b> 1ª caverna da proa (Baliza 10, a 4,44 m do espelho / 9,1% de L) · Área 0,25 m² · Chapa de 9,0 mm.<br/>"
    "  - <b>Antepara de Ré:</b> 1ª caverna da popa (Baliza 1, a 0,44 m do espelho / 9,1% de L) · Área 1,29 m² · Chapa de 9,0 mm.<br/>"
    "• <b>Quadro de Pesos e Centros da Estrutura:</b><br/>"
    "  - Chapeamento Total: <b>88 kg</b> | Reforços Estruturais: <b>181 kg</b> | Anteparas: <b>19 kg</b>.<br/>"
    "  - <b>Peso da Estrutura Nua:</b> <b>288 kg</b> (29,7% do deslocamento total).<br/>"
    "  - <b>Peso com Margem de Construção (12%):</b> <b>322 kg</b>.<br/>"
    "  - <b>Centro de Gravidade Longitudinal (L_CG):</b> <b>2,09 m do espelho</b> (43,0% do comprimento total).<br/>"
    "  - <b>Centro de Gravidade Vertical (V_CG):</b> <b>0,592 m acima da linha de base</b>.<br/>"
    "• <b>Conferência de Regras:</b> Todas as 32 verificações estruturais passaram com 100% de conformidade."
)

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 4.88m gerado com sucesso em:", pdf_path)
