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

# Load table of offsets
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/Plano_de_Linhas_Caliandra.pdf"

# Create A3 landscape figure
fig = plt.figure(figsize=(16.54, 11.69), dpi=300) # A3 landscape
plt.subplots_adjust(left=0.06, right=0.96, top=0.91, bottom=0.07)

# Header
fig.suptitle("PLANO DE LINHAS (LINES PLAN) — PROJETO O RESGATE", fontsize=16, fontweight="bold", y=0.97, color="#1F2429")
fig.text(0.5, 0.935, "Lancha de Resgate SAR 9.0m | Casco Deep-V Hard Chine em Alumínio Naval 5083 | 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
ax_prof.set_title("VISTA DE PERFIL (PROFILE / ELEVATION)", fontsize=11, fontweight="bold", color="#C4262E", pad=6, loc="left")
ax_prof.plot(xs, sheer_hts, color="#C4262E", lw=2, label="Borda (Sheer)")
ax_prof.plot(xs, chine_hts, color="#2E6B72", lw=1.8, ls="--", label="Quina (Chine)")
ax_prof.plot(xs, keel_hts, color="#1F2429", lw=2, label="Quilha (Keel / Base)")

# Waterline WL at 0.61m
ax_prof.axhline(0.61, color="#0077BE", lw=1.2, ls="-.", label="Linha d'Água de Projeto (DWL = 0,61 m | Δ = 5.262 kg)")

for s in stations:
    ax_prof.axvline(s["x"], color="#D3D9DC", lw=0.5, ls=":")
    ax_prof.text(s["x"], -0.15, f"B{s['stn']}", ha="center", va="top", fontsize=5.5, color="#5A626B")

ax_prof.set_ylabel("Altura Z (m)", fontsize=9, fontweight="bold")
ax_prof.set_ylim(-0.2, 1.8)
ax_prof.set_xlim(-0.3, 9.3)
ax_prof.grid(True, linestyle=":", alpha=0.6)
ax_prof.legend(loc="upper left", fontsize=8, framealpha=0.9)

# 2. PLAN VIEW (HALF-BREADTH)
ax_plan.set_title("VISTA SUPERIOR / MEIA-BOCA (PLAN / HALF-BREADTH)", fontsize=11, fontweight="bold", color="#C4262E", pad=6, loc="left")
ax_plan.plot(xs, sheer_hbs, color="#C4262E", lw=2, label="Meia-boca Borda (Sheer HB)")
ax_plan.plot(xs, chine_hbs, color="#2E6B72", lw=1.8, ls="--", label="Meia-boca Quina (Chine HB)")
ax_plan.plot(xs, [0]*len(xs), color="#1F2429", lw=1.5, label="Linha de Centro (CL)")

for s in stations:
    ax_plan.axvline(s["x"], color="#D3D9DC", lw=0.5, ls=":")
    ax_plan.plot([s["x"], s["x"]], [0, s["sheer_hb"]], color="#8E969C", lw=0.6)

ax_plan.set_ylabel("Meia-Boca Y (m)", fontsize=9, fontweight="bold")
ax_plan.set_xlabel("Comprimento X (m) [18 intervalos espaçados a cada 500 mm]", fontsize=9, fontweight="bold")
ax_plan.set_ylim(-0.1, 1.7)
ax_plan.grid(True, linestyle=":", alpha=0.6)
ax_plan.legend(loc="upper left", fontsize=8, framealpha=0.9)

# 3. BODY PLAN (BALIZAS)
ax_body.set_title("PLANO DE BALIZAS (BODY PLAN)", fontsize=11, fontweight="bold", color="#C4262E", pad=6)
for s in stations:
    stn = s["stn"]
    if stn <= 10:
        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:
        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="#1F2429", lw=1.5, ls="-")
ax_body.axhline(0.61, color="#0077BE", lw=1.2, ls="-.", label="DWL (0,61m)")
ax_body.text(-1.3, 0.63, "DWL", color="#0077BE", fontsize=8, fontweight="bold")
ax_body.text(-0.8, 1.6, "<- POPA (B1 a B10)", fontsize=7.5, fontweight="bold", color="#2E6B72", ha="center")
ax_body.text(0.8, 1.6, "PROA (B11 a B19) ->", fontsize=7.5, fontweight="bold", color="#C4262E", ha="center")

ax_body.set_xlabel("Meia-Boca Y (m)", fontsize=9, fontweight="bold")
ax_body.set_ylabel("Altura Z (m)", fontsize=9, fontweight="bold")
ax_body.set_xlim(-1.7, 1.7)
ax_body.set_ylim(-0.1, 1.7)
ax_body.grid(True, linestyle=":", alpha=0.6)

# 4. OFFSET TABLE & HYDROSTATICS SUMMARY
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.60, 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,00 m\n"
    "• Comprimento Linha d'Água (LWL): 7,36 m\n"
    "• Boca Máxima (BOA): 3,05 m\n"
    "• Boca Linha d'Água (BWL): 2,55 m\n"
    "• Calado de Projeto (T): 0,61 m\n"
    "• Deslocamento de Projeto: 5.262 kg\n"
    "• Volume Deslocado (∇): 5,134 m³\n"
    "• Coeficiente de Bloco (Cb): 0,445\n"
    "• Coef. Seção Mestra (Cm): 0,689\n"
    "• Deformação na Planificação: 0,007%\n"
    "• Espaçamento entre Balizas: 500,0 mm\n"
    "• Material: Alumínio Naval 5083\n"
    "• Propulsão: 2x 300 HP Outboard"
)
ax_info.text(0.64, 0.98, info_box_text, va="top", ha="left", fontsize=7.5,
             bbox=dict(boxstyle="round,pad=0.5", facecolor="#EFF2F3", edgecolor="#D3D9DC", lw=1))

# Footer note on drawing
fig.text(0.06, 0.03, "BRANA · Escola de Arquitetura e Engenharia Naval | Estaleiro Escola Embrião — Salvador, BA", fontsize=8, color="#5A626B")
fig.text(0.94, 0.03, "Documento Técnico de Engenharia Naval — 19 Balizas (ΔX = 500 mm) — Escala 1:25", fontsize=8, color="#5A626B", ha="right")

plt.savefig(pdf_path, format="pdf", dpi=300)
plt.close()
print("PDF do Plano de Linhas atualizado!")
