import json
import matplotlib.pyplot as plt
import numpy as np
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, Image as RLImage
)
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.pdfgen import canvas

# 1. Dados da Tabela de Cotas
cotas = [
    # stn, x, sheer_hb, chine_hb, sheer_ht, chine_ht, keel_ht, deadrise
    (1, 0, 920.0, 740.0, 850.0, 247.6, 0.0, 18.50),
    (2, 697, 975.1, 784.9, 850.0, 248.6, 0.0, 17.58),
    (3, 1394, 1005.8, 814.8, 850.0, 257.9, 0.0, 17.56),
    (4, 2091, 1024.9, 820.0, 850.0, 278.8, 0.0, 18.78),
    (5, 2789, 992.4, 774.2, 850.0, 306.9, 0.0, 21.63),
    (6, 3486, 874.9, 656.4, 850.0, 362.4, 0.0, 28.90),
    (7, 4183, 577.4, 418.1, 855.3, 534.4, 191.1, 39.39),
    (8, 4880, 0.0, 0.0, 880.0, 880.0, 880.0, 0.00),
]

x_vals = [c[1] for c in cotas]
sheer_hb = [c[2] for c in cotas]
chine_hb = [c[3] for c in cotas]
sheer_ht = [c[4] for c in cotas]
chine_ht = [c[5] for c in cotas]
keel_ht = [c[6] for c in cotas]

# Interpolação suave usando numpy interp com pontos densos
x_smooth = np.linspace(0, 4880, 300)
sheer_hb_smooth = np.interp(x_smooth, x_vals, sheer_hb)
chine_hb_smooth = np.interp(x_smooth, x_vals, chine_hb)
sheer_ht_smooth = np.interp(x_smooth, x_vals, sheer_ht)
chine_ht_smooth = np.interp(x_smooth, x_vals, chine_ht)
keel_ht_smooth = np.interp(x_smooth, x_vals, keel_ht)

# Plot 1: Plano de Linhas Longitudinal (Perfil e Planta)
fig, (ax_side, ax_top) = plt.subplots(2, 1, figsize=(11, 6), sharex=True, dpi=200)
fig.patch.set_facecolor('#ffffff')

# Side View (Perfil)
ax_side.set_facecolor('#fbfcfd')
ax_side.plot(x_smooth, sheer_ht_smooth, color='#1A365D', lw=2.2, label='Borda (Sheer)')
ax_side.plot(x_smooth, chine_ht_smooth, color='#2B6CB0', lw=1.8, label='Chine (Quina)')
ax_side.plot(x_smooth, keel_ht_smooth, color='#C53030', lw=2.0, label='Quilha (Keel)')
ax_side.scatter(x_vals, sheer_ht, color='#1A365D', s=25, zorder=5)
ax_side.scatter(x_vals, chine_ht, color='#2B6CB0', s=25, zorder=5)
ax_side.scatter(x_vals, keel_ht, color='#C53030', s=25, zorder=5)

for stn, x, _, _, _, _, _, _ in cotas:
    ax_side.axvline(x, color='#CBD5E0', ls='--', lw=0.7)
    ax_side.text(x, -50, f'Stn {stn}', ha='center', va='top', fontsize=8, color='#4A5568')

ax_side.set_title('Plano de Alto e Baixo (Perfil Longitudinal)', fontsize=11, fontweight='bold', color='#1A365D', pad=8)
ax_side.set_ylabel('Altura [mm]', fontsize=9, fontweight='bold', color='#2D3748')
ax_side.set_ylim(-80, 1000)
ax_side.grid(True, ls=':', color='#E2E8F0')
ax_side.legend(loc='upper left', fontsize=8, framealpha=0.9)

# Top View (Planta)
ax_top.set_facecolor('#fbfcfd')
ax_top.plot(x_smooth, sheer_hb_smooth, color='#1A365D', lw=2.2, label='Meia-boca da Borda')
ax_top.plot(x_smooth, chine_hb_smooth, color='#2B6CB0', lw=1.8, label='Meia-boca do Chine')
ax_top.plot(x_smooth, -sheer_hb_smooth, color='#1A365D', lw=1.2, ls=':')
ax_top.plot(x_smooth, -chine_hb_smooth, color='#2B6CB0', lw=1.0, ls=':')
ax_top.axhline(0, color='#718096', lw=1.0, ls='-.', label='Linha de Centro (CL)')
ax_top.scatter(x_vals, sheer_hb, color='#1A365D', s=25, zorder=5)
ax_top.scatter(x_vals, chine_hb, color='#2B6CB0', s=25, zorder=5)

for _, x, _, _, _, _, _, _ in cotas:
    ax_top.axvline(x, color='#CBD5E0', ls='--', lw=0.7)

ax_top.set_title('Plano de Linhas D\'água (Planta / Vista Superior)', fontsize=11, fontweight='bold', color='#1A365D', pad=8)
ax_top.set_xlabel('Posição Longitudinal X [mm] (0 = Espelho de Popa, 4880 = Roda de Proa)', fontsize=9, fontweight='bold', color='#2D3748')
ax_top.set_ylabel('Meia-Boca [mm]', fontsize=9, fontweight='bold', color='#2D3748')
ax_top.set_ylim(-1150, 1150)
ax_top.grid(True, ls=':', color='#E2E8F0')
ax_top.legend(loc='upper right', fontsize=8, framealpha=0.9)

plt.tight_layout()
fig_long_path = "/home/magdalena/eee/alunos/victor-lei/fig_plano_linhas_longitudinal.png"
plt.savefig(fig_long_path, dpi=200)
plt.close()

# Plot 2: Plano de Balizas / Body Plan
fig, ax_body = plt.subplots(figsize=(7, 5), dpi=200)
fig.patch.set_facecolor('#ffffff')
ax_body.set_facecolor('#fbfcfd')

# Lado direito: Balizas 5 a 8 (Proa / Vante)
# Lado esquerdo: Balizas 1 a 4 (Popa / Ré)
for c in cotas:
    stn, x, s_hb, c_hb, s_ht, c_ht, k_ht, deadrise = c
    if stn >= 5: # Vante (lado direito, x positivo)
        y_pts = [0, c_hb, s_hb]
        z_pts = [k_ht, c_ht, s_ht]
        color = '#2B6CB0' if stn < 8 else '#1A365D'
        lbl = f'Baliza {stn}' if stn < 8 else 'Baliza 8 (Proa)'
        ax_body.plot(y_pts, z_pts, lw=2.0, color=color, label=lbl)
        if stn < 8:
            ax_body.text(s_hb + 25, s_ht, f'Stn {stn}', va='center', fontsize=8, color=color, fontweight='bold')
    else: # Ré (lado esquerdo, x negativo)
        y_pts = [0, -c_hb, -s_hb]
        z_pts = [k_ht, c_ht, s_ht]
        color = '#C53030' if stn == 1 else '#DD6B20'
        lbl = f'Baliza {stn}' if stn > 1 else 'Baliza 1 (Espelho)'
        ax_body.plot(y_pts, z_pts, lw=2.0, color=color, label=lbl)
        ax_body.text(-s_hb - 25, s_ht, f'Stn {stn}', ha='right', va='center', fontsize=8, color=color, fontweight='bold')

# Linhas de referência
ax_body.axvline(0, color='#1A365D', lw=1.2, ls='-.', label='Linha de Centro')
ax_body.axhline(0, color='#718096', lw=1.0, ls='-', label='Linha Base (Quilha)')

# Linha d'água de projeto (calado 352 mm)
ax_body.axhline(352, color='#319795', lw=1.5, ls='--', label='Linha D\'água (DWL = 352 mm)')

ax_body.set_title('Plano de Balizas (Body Plan / Seções Transversais)\n[← Ré / Popa | Vante / Proa →]', fontsize=11, fontweight='bold', color='#1A365D', pad=10)
ax_body.set_xlabel('Meia-Boca [mm]', fontsize=9, fontweight='bold', color='#2D3748')
ax_body.set_ylabel('Altura acima da Linha Base [mm]', fontsize=9, fontweight='bold', color='#2D3748')
ax_body.set_xlim(-1250, 1250)
ax_body.set_ylim(-50, 950)
ax_body.grid(True, ls=':', color='#E2E8F0')
ax_body.legend(loc='lower center', fontsize=7.5, ncol=3, framealpha=0.9)

plt.tight_layout()
fig_body_path = "/home/magdalena/eee/alunos/victor-lei/fig_plano_balizas.png"
plt.savefig(fig_body_path, dpi=200)
plt.close()

# 2. Construir o documento PDF com ReportLab
pdf_path = "/home/magdalena/eee/alunos/victor-lei/Plano_de_Linhas_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 — PLANO DE LINHAS & TABELA DE COTAS")
            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")
cor_secundaria = colors.HexColor("#2B6CB0")
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,
    leading=10,
    textColor=colors.white,
    alignment=1
)

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

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

story = []

# Título
story.append(Paragraph("PLANO DE LINHAS & TABELA DE COTAS", 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))

intro_text = (
    "<b>Definição Geométrica:</b> Casco de planeio em 'V' moderado com quina viva (<i>hard chine</i>), "
    "dimensionado para operação em águas abrigadas de represa e enseadas costeiras. O traçado é definido por "
    "8 balizas igualmente espaçadas, com transição suave de deadrise desde a entrada profunda na proa (39,39°) "
    "até o fundo de sustentação no espelho de popa (18,50°)."
)
t_intro = Table([[Paragraph(intro_text, style_corpo)]], 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. Tabela de Cotas Oficial (Offsets Table)
t_h1 = Table([[Paragraph("1. TABELA DE COTAS (OFFSETS) — VALORES EM MILÍMETROS", 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)

tabela_rows = [
    [
        Paragraph("Baliza<br/>(Stn)", style_th),
        Paragraph("Posição X<br/>[mm]", style_th),
        Paragraph("Meia-Boca<br/>Borda [mm]", style_th),
        Paragraph("Meia-Boca<br/>Chine [mm]", style_th),
        Paragraph("Altura<br/>Borda [mm]", style_th),
        Paragraph("Altura<br/>Chine [mm]", style_th),
        Paragraph("Altura<br/>Quilha [mm]", style_th),
        Paragraph("Ângulo V<br/>(Deadrise)", style_th)
    ]
]

for c in cotas:
    stn, x, s_hb, c_hb, s_ht, c_ht, k_ht, deadrise = c
    tabela_rows.append([
        Paragraph(f"<b>{stn}</b>", style_td),
        Paragraph(f"{x:.1f}", style_td),
        Paragraph(f"{s_hb:.1f}", style_td),
        Paragraph(f"{c_hb:.1f}", style_td),
        Paragraph(f"{s_ht:.1f}", style_td),
        Paragraph(f"{c_ht:.1f}", style_td),
        Paragraph(f"{k_ht:.1f}", style_td),
        Paragraph(f"<b>{deadrise:.2f}°</b>", style_td),
    ])

t_cotas = Table(tabela_rows, colWidths=[48, 62, 68, 68, 65, 65, 65, 63])
t_cotas.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_cotas)
story.append(Spacer(1, 10))

# Imagem do Traçado Longitudinal
story.append(KeepTogether([
    Table([[Paragraph("2. TRAÇADO LONGITUDINAL (PLANTA E PERFIL)", style_secao_titulo)]], colWidths=[504],
          style=[('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)]),
    Spacer(1, 4),
    Table([[RLImage(fig_long_path, width=504, height=270)]], colWidths=[504],
          style=[('ALIGN', (0,0), (-1,-1), 'CENTER'), ('BOX', (0,0), (-1,-1), 0.5, cor_borda), ('TOPPADDING', (0,0), (-1,-1), 2), ('BOTTOMPADDING', (0,0), (-1,-1), 2)])
]))

story.append(PageBreak())

# Imagem do Plano de Balizas (Body Plan)
story.append(KeepTogether([
    Table([[Paragraph("3. PLANO DE BALIZAS (BODY PLAN / SEÇÕES TRANSVERSAIS)", style_secao_titulo)]], colWidths=[504],
          style=[('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)]),
    Spacer(1, 4),
    Table([[RLImage(fig_body_path, width=460, height=310)]], colWidths=[504],
          style=[('ALIGN', (0,0), (-1,-1), 'CENTER'), ('BOX', (0,0), (-1,-1), 0.5, cor_borda), ('TOPPADDING', (0,0), (-1,-1), 4), ('BOTTOMPADDING', (0,0), (-1,-1), 4)])
]))
story.append(Spacer(1, 12))

# 4. Síntese Hidrostática e Geométrica
t_h4 = Table([[Paragraph("4. SÍNTESE GEOMÉTRICA & HIDROSTÁTICA DA CARENA", style_secao_titulo)]], colWidths=[504])
t_h4.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_h4)

sintese_data = [
    [Paragraph("Comprimento Total (LOA)", style_td_label), Paragraph("4,880 m", style_td), Paragraph("Boca Moldada Máxima (BOA)", style_td_label), Paragraph("2,050 m (Stn 4)", style_td)],
    [Paragraph("Comprimento Linha D'água (LWL)", style_td_label), Paragraph("4,420 m", style_td), Paragraph("Boca Linha D'água (BWL)", style_td_label), Paragraph("1,750 m", style_td)],
    [Paragraph("Pontal Moldado (D)", style_td_label), Paragraph("0,850 m a 0,880 m", style_td), Paragraph("Calado de Projeto (T)", style_td_label), Paragraph("0,352 m", style_td)],
    [Paragraph("Deslocamento de Projeto", style_td_label), Paragraph("1.295 kg (água doce)", style_td), Paragraph("Área Seção Mestra (Am)", style_td_label), Paragraph("0,367 m²", style_td)],
    [Paragraph("Coeficiente de Bloco (Cb)", style_td_label), Paragraph("0,480", style_td), Paragraph("Coeficiente de Seção Mestra (Cm)", style_td_label), Paragraph("0,615", style_td)],
    [Paragraph("Razão Comprimento/Boca", style_td_label), Paragraph("2,38", style_td), Paragraph("Volume de Carena (∇)", style_td_label), Paragraph("1,264 m³", style_td)],
]

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

doc.build(story, canvasmaker=NumberedCanvas)

# Copiar para a pasta do grupo 6
import shutil
shutil.copy(pdf_path, "/home/magdalena/eee/grupos/grupo-6/Plano_de_Linhas_Victor_Lei.pdf")

print("PDF do Plano de Linhas gerado com sucesso!")
