import json
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/Tabela_de_Cotas_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, "Tabela de Cotas Oficial (Offsets Table)")
        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=11,
    leading=15,
    textColor=colors.HexColor("#C4262E"),
    spaceBefore=8,
    spaceAfter=3
)

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

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("Tabela de Cotas Oficial (Table of Offsets)", 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))

# Info Box
intro_p = (
    "<b>Notas Técnicas de Referência:</b><br/>"
    "• <b>Comprimento Total (LOA):</b> 9,000 m (18 intervalos regulares de 500,00 mm com 19 balizas).<br/>"
    "• <b>Sistema de Coordenadas:</b> Meias-bocas (Y) medidas a partir da Linha de Centro (CL); "
    "Alturas (Z) medidas acima da Linha de Base (BL — ponto mais baixo da quilha). Todas as cotas em <b>milímetros (mm)</b>.<br/>"
    "• <b>Geometria Desenvolvível:</b> Transição contínua e alisamento de geratrizes cônicas na proa (deformação na planificação < 0,01%)."
)
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, 6))

# Tabela
story.append(Paragraph("Cotas Milimétricas das 19 Balizas (B1 a B19)", sec_title_style))
story.append(HRFlowable(width="100%", thickness=0.5, color=colors.HexColor("#C4262E"), spaceAfter=5, spaceBefore=0))

cotas_raw = [
    [1, 0, 1500.0, 1100.0, 1100.0, 300.0, 0.0, 15.26],
    [2, 500, 1519.8, 1111.4, 1098.0, 299.2, -5.0, 15.31],
    [3, 1000, 1527.1, 1114.6, 1097.0, 301.3, -5.0, 15.37],
    [4, 1500, 1522.1, 1109.6, 1097.0, 306.3, 0.0, 15.43],
    [5, 2000, 1504.8, 1096.4, 1098.0, 314.2, 10.0, 15.51],
    [6, 2500, 1475.0, 1075.0, 1100.0, 325.0, 25.0, 15.59],
    [7, 3000, 1438.2, 1048.6, 1103.0, 340.8, 45.0, 15.75],
    [8, 3500, 1399.9, 1020.4, 1107.0, 363.7, 70.0, 16.06],
    [9, 4000, 1359.9, 990.4, 1112.0, 393.7, 100.0, 16.52],
    [10, 4500, 1318.2, 958.6, 1118.0, 430.8, 135.0, 17.15],
    [11, 5000, 1275.0, 925.0, 1125.0, 475.0, 175.0, 17.97],
    [12, 5500, 1217.3, 880.9, 1135.8, 526.9, 227.8, 18.76],
    [13, 6000, 1132.2, 817.5, 1153.1, 587.3, 301.2, 19.29],
    [14, 6500, 1019.8, 734.9, 1176.9, 656.1, 395.3, 19.54],
    [15, 7000, 880.1, 633.1, 1207.3, 733.3, 509.9, 19.43],
    [16, 7500, 712.1, 511.4, 1244.4, 818.3, 643.7, 18.85],
    [17, 8000, 509.9, 365.7, 1288.8, 908.1, 787.4, 18.26],
    [18, 8500, 272.5, 195.2, 1340.7, 1002.0, 939.5, 17.75],
    [19, 9000, 0.0, 0.0, 1400.0, 1100.0, 1100.0, 0.0]
]

table_data = [
    [
        Paragraph("Baliza", th_style),
        Paragraph("X (mm)", th_style),
        Paragraph("Meia-Boca<br/>Borda (Y)", th_style),
        Paragraph("Meia-Boca<br/>Chine (Y)", th_style),
        Paragraph("Altura<br/>Borda (Z)", th_style),
        Paragraph("Altura<br/>Chine (Z)", th_style),
        Paragraph("Altura<br/>Quilha (Z)", th_style),
        Paragraph("Ângulo V<br/>(Deadrise)", th_style)
    ]
]

for r in cotas_raw:
    b_label = f"B{r[0]}"
    if r[0] == 1:
        b_label += " (Espelho)"
    elif r[0] == 10:
        b_label += " (Meia-Nau)"
    elif r[0] == 19:
        b_label += " (Proa)"
        
    table_data.append([
        Paragraph(b_label, td_left),
        Paragraph(f"{r[1]}", td_style),
        Paragraph(f"{r[2]:.1f}".replace(".", ","), td_style),
        Paragraph(f"{r[3]:.1f}".replace(".", ","), td_style),
        Paragraph(f"{r[4]:.1f}".replace(".", ","), td_style),
        Paragraph(f"{r[5]:.1f}".replace(".", ","), td_style),
        Paragraph(f"{r[6]:.1f}".replace(".", ","), td_style),
        Paragraph(f"{r[7]:.2f}°".replace(".", ","), td_style)
    ])

t_elem = Table(table_data, colWidths=[80, 55, 62, 62, 60, 60, 60, 65])
t_elem.setStyle(TableStyle([
    ("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#1F2429")),
    ("BACKGROUND", (0, 1), (-1, 1), colors.HexColor("#F3E8FF")),   # B1 Espelho
    ("BACKGROUND", (0, 10), (-1, 10), colors.HexColor("#FEF3C7")), # B10 Meia-nau
    ("BACKGROUND", (0, 19), (-1, 19), colors.HexColor("#E0F2FE")), # B19 Proa
    ("GRID", (0, 0), (-1, -1), 0.5, colors.HexColor("#CBD5E1")),
    ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
    ("TOPPADDING", (0, 0), (-1, -1), 2.5),
    ("BOTTOMPADDING", (0, 0), (-1, -1), 2.5),
]))
story.append(t_elem)
story.append(Spacer(1, 6))

# Resumo Hidrostático no Rodapé
resumo_p = (
    "<b>Resumo dos Resultados Hidrostáticos de Carena (DWL = 0,61 m em Água Salgada):</b><br/>"
    "• <b>Deslocamento (Δ):</b> 5.262 kg | <b>Volume Submerso (∇):</b> 5,134 m³<br/>"
    "• <b>LWL:</b> 7,36 m | <b>BWL:</b> 2,55 m | <b>Cb:</b> 0,445 | <b>Cm:</b> 0,689 | <b>DLR:</b> 371<br/>"
    "• <b>Desenvolvibilidade:</b> Conformação 100% elástica com deformação pico de 0,007% no Costado."
)
resumo_tab = Table([[Paragraph(resumo_p, p_style)]], colWidths=[504])
resumo_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(resumo_tab)

doc.build(story, canvasmaker=NumberedCanvas)
print("PDF da Tabela de Cotas gerado com sucesso em:", pdf_path)
