import json, math
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np

# Load exact offset table
tabela_path = "/home/magdalena/eee/alunos/caliandra/tabela_cotas_caliandra.txt"
stations = []
with open(tabela_path, "r") as f:
    for line in f:
        line = line.strip()
        if not line or line.startswith("#"):
            continue
        parts = line.split()
        if len(parts) >= 7:
            stn = int(parts[0])
            x = float(parts[1]) / 1000.0
            sheer_hb = float(parts[2]) / 1000.0
            chine_hb = float(parts[3]) / 1000.0
            sheer_ht = float(parts[4]) / 1000.0
            chine_ht = float(parts[5]) / 1000.0
            keel_ht = float(parts[6]) / 1000.0
            deadrise = float(parts[7]) if len(parts) > 7 else 0.0
            stations.append({
                "stn": stn, "x": x,
                "sheer_hb": sheer_hb, "chine_hb": chine_hb,
                "sheer_ht": sheer_ht, "chine_ht": chine_ht,
                "keel_ht": keel_ht, "deadrise": deadrise
            })

pdf_path = "/home/magdalena/eee/alunos/caliandra/Grafico_de_Linhas_Caliandra.pdf"

# Create A3 Landscape figure (420 x 297 mm -> 16.54 x 11.69 in)
fig = plt.figure(figsize=(16.54, 11.69), dpi=300)
plt.subplots_adjust(left=0.05, right=0.95, top=0.91, bottom=0.07)

# Main Title & Subtitle
fig.suptitle("GRÁFICO DO PLANO DE LINHAS OFICIAL (LINES PLAN DRAWING)", fontsize=16, fontweight="bold", y=0.97, color="#1F2429")
fig.text(0.5, 0.935, "Lancha de Resgate Rápido SAR 9.0m — O RESGATE | 19 Balizas (B1 a B19 — ΔX = 500 mm) | Projetista: Caliandra | Escala 1:25", 
         ha="center", fontsize=10, color="#5A626B", fontstyle="italic")

ax_prof = plt.subplot2grid((3, 3), (0, 0), colspan=3)
ax_plan = plt.subplot2grid((3, 3), (1, 0), colspan=3, sharex=ax_prof)
ax_body = plt.subplot2grid((3, 3), (2, 0), colspan=1)
ax_info = plt.subplot2grid((3, 3), (2, 1), colspan=2)

xs = [s["x"] for s in stations]
sheer_hts = [s["sheer_ht"] for s in stations]
chine_hts = [s["chine_ht"] for s in stations]
keel_hts = [s["keel_ht"] for s in stations]

sheer_hbs = [s["sheer_hb"] for s in stations]
chine_hbs = [s["chine_hb"] for s in stations]

# -------------------------------------------------------------
# 1. PROFILE VIEW (PERFIL LONGITUDINAL)
# -------------------------------------------------------------
ax_prof.set_title("1. VISTA DE PERFIL (PROFILE / SHEER PLAN)", fontsize=11, fontweight="bold", color="#C4262E", pad=5, loc="left")
ax_prof.plot(xs, sheer_hts, color="#C4262E", lw=2.2, label="Linha da Borda (Sheer Line)")
ax_prof.plot(xs, chine_hts, color="#2E6B72", lw=1.8, ls="--", label="Linha da Quina (Chine Line)")
ax_prof.plot(xs, keel_hts, color="#1F2429", lw=2.2, label="Linha da Quilha (Keel Line)")

# DWL (Linha d'Água Z = 0,61 m)
ax_prof.axhline(0.61, color="#0284C7", lw=1.3, ls="-.", label="Linha d'Água de Projeto (DWL = 0,61 m)")
ax_prof.axhline(0.00, color="#DC2626", lw=1.0, ls=":", label="Linha de Base (BL = 0,00 m)")

# Stations grid lines and markers
for s in stations:
    ax_prof.axvline(s["x"], color="#E2E8F0", lw=0.5, ls=":")
    ax_prof.plot(s["x"], s["sheer_ht"], marker="^", markersize=3.5, color="#C4262E")
    ax_prof.plot(s["x"], s["chine_ht"], marker="o", markersize=3.5, color="#2E6B72")
    ax_prof.plot(s["x"], s["keel_ht"], marker="s", markersize=3.0, color="#1F2429")
    ax_prof.text(s["x"], -0.15, f"B{s['stn']}", ha="center", va="top", fontsize=5.8, color="#5A626B")

ax_prof.set_ylabel("Altura Z (m)", fontsize=8.5, fontweight="bold")
ax_prof.set_ylim(-0.25, 1.7)
ax_prof.set_xlim(-0.4, 9.4)
ax_prof.grid(True, linestyle=":", alpha=0.5)
ax_prof.legend(loc="upper left", fontsize=7.5, ncol=3, framealpha=0.95)

# -------------------------------------------------------------
# 2. PLAN VIEW (VISTA EM PLANTA / MEIAS-BOCAS)
# -------------------------------------------------------------
ax_plan.set_title("2. VISTA EM PLANTA (HALF-BREADTH PLAN)", fontsize=11, fontweight="bold", color="#C4262E", pad=5, loc="left")
ax_plan.plot(xs, sheer_hbs, color="#C4262E", lw=2.2, label="Meia-Boca da Borda (Sheer HB)")
ax_plan.plot(xs, chine_hbs, color="#2E6B72", lw=1.8, ls="--", label="Meia-Boca da Quina (Chine HB)")
ax_plan.plot(xs, [0]*len(xs), color="#2563EB", lw=1.5, label="Linha de Centro (CL)")

for s in stations:
    ax_plan.axvline(s["x"], color="#E2E8F0", lw=0.5, ls=":")
    ax_plan.plot(s["x"], s["sheer_hb"], marker="^", markersize=3.5, color="#C4262E")
    ax_plan.plot(s["x"], s["chine_hb"], marker="o", markersize=3.5, color="#2E6B72")
    ax_plan.plot(s["x"], 0.0, marker="s", markersize=2.5, color="#2563EB")
    ax_plan.plot([s["x"], s["x"]], [0, s["sheer_hb"]], color="#CBD5E1", lw=0.6)

ax_plan.set_ylabel("Meia-Boca Y (m)", fontsize=8.5, fontweight="bold")
ax_plan.set_xlabel("Distância Longitudinal X (m) [18 intervalos espaçados a cada 500,0 mm]", fontsize=8.5, fontweight="bold")
ax_plan.set_ylim(-0.15, 1.7)
ax_plan.set_xlim(-0.4, 9.4)
ax_plan.grid(True, linestyle=":", alpha=0.5)
ax_plan.legend(loc="upper left", fontsize=7.5, ncol=3, framealpha=0.95)

# -------------------------------------------------------------
# 3. BODY PLAN (PLANO DE BALIZAS TRANSVERSAIS)
# -------------------------------------------------------------
ax_body.set_title("3. PLANO DE BALIZAS (BODY PLAN)", fontsize=11, fontweight="bold", color="#C4262E", pad=5)
for s in stations:
    stn = s["stn"]
    if stn <= 10: # POPA (B1 a B10) -> Esquerda (-Y)
        y_pts = [0.0, -s["chine_hb"], -s["sheer_hb"]]
        z_pts = [s["keel_ht"], s["chine_ht"], s["sheer_ht"]]
        color = "#1F2429" if stn == 10 else "#2E6B72"
        lw = 2.0 if stn == 10 else 0.9
        ax_body.plot(y_pts, z_pts, color=color, lw=lw)
        ax_body.text(-s["sheer_hb"]-0.03, s["sheer_ht"], f"B{stn}", ha="right", va="center", fontsize=5.8, color=color, fontweight="bold" if stn==10 else "normal")
    else: # PROA (B11 a B19) -> Direita (+Y)
        y_pts = [0.0, s["chine_hb"], s["sheer_hb"]]
        z_pts = [s["keel_ht"], s["chine_ht"], s["sheer_ht"]]
        color = "#C4262E"
        lw = 0.9
        ax_body.plot(y_pts, z_pts, color=color, lw=lw)
        if s["sheer_hb"] > 0.05:
            ax_body.text(s["sheer_hb"]+0.03, s["sheer_ht"], f"B{stn}", ha="left", va="center", fontsize=5.8, color=color)

ax_body.axvline(0, color="#2563EB", lw=1.5, ls="-", label="CL (Y=0)")
ax_body.axhline(0.61, color="#0284C7", lw=1.2, ls="-.", label="DWL (Z=0,61m)")
ax_body.axhline(0.00, color="#DC2626", lw=1.0, ls=":", label="BL (Z=0)")

ax_body.text(-0.8, 1.55, "← POPA (B1 a B10)", fontsize=7.5, fontweight="bold", color="#2E6B72", ha="center")
ax_body.text(0.8, 1.55, "PROA (B11 a B19) →", fontsize=7.5, fontweight="bold", color="#C4262E", ha="center")

ax_body.set_xlabel("Meia-Boca Y (m)", fontsize=8.5, fontweight="bold")
ax_body.set_ylabel("Altura Z (m)", fontsize=8.5, fontweight="bold")
ax_body.set_xlim(-1.7, 1.7)
ax_body.set_ylim(-0.15, 1.7)
ax_body.grid(True, linestyle=":", alpha=0.5)
ax_body.legend(loc="upper left", fontsize=6.8)

# -------------------------------------------------------------
# 4. TABELA DE OFFSETS & QUADRO HIDROSTÁTICO
# -------------------------------------------------------------
ax_info.axis("off")
table_text_data = [
    ["Stn", "X (mm)", "Sheer HB", "Chine HB", "Sheer Z", "Chine Z", "Keel Z", "Deadrise"]
]
for s in stations:
    table_text_data.append([
        f"B{s['stn']}",
        f"{int(round(s['x']*1000))}",
        f"{s['sheer_hb']:.1f}",
        f"{s['chine_hb']:.1f}",
        f"{s['sheer_ht']:.1f}",
        f"{s['chine_ht']:.1f}",
        f"{s['keel_ht']:.1f}",
        f"{s['deadrise']:.2f}°"
    ])

table = ax_info.table(
    cellText=table_text_data,
    colLabels=None,
    loc="upper left",
    bbox=[0.0, 0.02, 0.58, 0.98]
)
table.auto_set_font_size(False)
table.set_fontsize(5.8)
for (row, col), cell in table.get_celld().items():
    if row == 0:
        cell.set_facecolor("#1F2429")
        cell.set_text_props(color="white", fontweight="bold")
    elif row == 10: # Meia-Nau (B10)
        cell.set_facecolor("#FEF3C7")
        cell.set_text_props(fontweight="bold", color="#92400E")
    elif row % 2 == 1:
        cell.set_facecolor("#EFF2F3")
    cell.set_edgecolor("#D3D9DC")
    cell.set_height(0.044)

# Hydrostatics & Particulars Box
info_box_text = (
    "PRINCIPAIS CARACTERÍSTICAS (19 BALIZAS):\n"
    "• Comprimento Total (LOA): 9,000 m\n"
    "• Comprimento Linha d'Água (LWL): 7,360 m\n"
    "• Boca Máxima (BOA): 3,054 m\n"
    "• Boca Linha d'Água (BWL): 2,550 m\n"
    "• Pontal na Meia-Nau (B10): 1,118 m\n"
    "• Pontal na Proa (B19): 1,400 m\n"
    "• Calado de Projeto (T): 0,610 m\n"
    "• Deslocamento de Projeto (Δ): 5.262 kg\n"
    "• Volume Deslocado (∇): 5,134 m³\n"
    "• Coeficiente de Bloco (Cb): 0,445\n"
    "• Coeficiente Seção Mestra (Cm): 0,689\n"
    "• Razão Desloc.-Comprimento (DLR): 371,0\n"
    "• Deformação na Planificação: 0,007%\n"
    "• Espaçamento entre Balizas: 500,0 mm\n"
    "• Material: Alumínio Naval 5083-H116\n"
    "• Propulsão: 2x 300 HP Outboard"
)
ax_info.text(0.62, 0.98, info_box_text, va="top", ha="left", fontsize=7.2,
             bbox=dict(boxstyle="round,pad=0.5", facecolor="#EFF2F3", edgecolor="#D3D9DC", lw=1))

# Footer
fig.text(0.05, 0.02, "BRANA · Escola de Arquitetura e Engenharia Naval | Estaleiro Escola Embrião — Salvador, BA", fontsize=7.5, color="#5A626B")
fig.text(0.95, 0.02, "Prancha Oficial de Traçado do Plano de Linhas — 19 Balizas — Escala 1:25", fontsize=7.5, color="#5A626B", ha="right")

plt.savefig(pdf_path, format="pdf", dpi=300)
plt.close()
print("PDF do Grafico de Linhas gerado com sucesso em:", pdf_path)
