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

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

# A3 Landscape
fig = plt.figure(figsize=(16.54, 11.69), dpi=300)
plt.subplots_adjust(left=0.05, right=0.95, top=0.92, bottom=0.07)

fig.suptitle("DEFINIÇÃO DA LINHA D'ÁGUA DE PROJETO (DWL) — CASCO COM 17 BALIZAS", fontsize=16, fontweight="bold", y=0.97, color="#1F2429")
fig.text(0.5, 0.94, "Estudo Hidrostático com 16 Intervalos (ΔX = 562,5 mm) | Projeto O RESGATE | Projetista: Caliandra | SI", 
         ha="center", fontsize=9.5, color="#5A626B", fontstyle="italic")

ax_prof = plt.subplot2grid((2, 2), (0, 0))
ax_curv = plt.subplot2grid((2, 2), (0, 1))
ax_body = plt.subplot2grid((2, 2), (1, 0))
ax_tab  = plt.subplot2grid((2, 2), (1, 1))

# 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
            })

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]

# 1. PERFIL
ax_prof.set_title("1. PERFIL LONGITUDINAL E LINHAS D'ÁGUA OPERACIONAIS", fontsize=11, fontweight="bold", color="#C4262E", loc="left", pad=5)
ax_prof.plot(xs, sheer_hts, color="#C4262E", lw=2, label="Borda (Sheer)")
ax_prof.plot(xs, chine_hts, color="#2E6B72", lw=1.5, ls="--", label="Quina (Chine)")
ax_prof.plot(xs, keel_hts, color="#1F2429", lw=2, label="Linha de Base / Quilha (Keel)")
ax_prof.fill_between(xs, keel_hts, sheer_hts, color="#F8FAFC", zorder=0)

ax_prof.axhline(0.45, color="#10B981", lw=1.5, ls=":", label="1. Linha Leve (Lightship: 4.082 kg | T = 0,45 m)")
ax_prof.axhline(0.52, color="#0284C7", lw=2.2, ls="-.", label="2. Linha d'Água de Projeto (DWL: 5.204 kg | T = 0,52 m)")
ax_prof.axhline(0.60, color="#F59E0B", lw=1.5, ls="--", label="3. Plena Carga Máxima (Full Load: 6.560 kg | T = 0,60 m)")

ax_prof.annotate("", xy=(4.5, 0.52), xytext=(4.5, 1.10), arrowprops=dict(arrowstyle="<->", color="#C4262E", lw=1.5))
ax_prof.text(4.65, 0.80, "Borda Livre Meia-Nau\nFb = 580 mm (0,58 m)", color="#C4262E", fontsize=8, fontweight="bold")

for s in stations:
    ax_prof.axvline(s["x"], color="#E2E8F0", lw=0.5, ls=":")
    ax_prof.text(s["x"], -0.12, f"B{s['stn']}", ha="center", fontsize=5.5, color="#64748B")

ax_prof.set_ylabel("Altura Z (m)", fontsize=8.5, fontweight="bold")
ax_prof.set_xlim(-0.5, 9.5)
ax_prof.set_ylim(-0.2, 1.7)
ax_prof.grid(True, linestyle=":", alpha=0.5)
ax_prof.legend(loc="upper left", fontsize=7.2, framealpha=0.95)

# 2. CURVAS HIDROSTÁTICAS
ax_curv.set_title("2. CURVAS HIDROSTÁTICAS EM ÁGUA SALGADA (d = 1.025 t/m³)", fontsize=11, fontweight="bold", color="#C4262E", loc="left", pad=5)
calados_m = [0.45, 0.50, 0.52, 0.54, 0.56, 0.58, 0.60]
deslocs_t = [4.082, 4.877, 5.204, 5.536, 5.873, 6.214, 6.560]
cbs       = [0.512, 0.528, 0.532, 0.536, 0.540, 0.543, 0.547]
cms       = [0.635, 0.658, 0.666, 0.673, 0.679, 0.685, 0.690]

ax_curv.plot(calados_m, deslocs_t, color="#0284C7", lw=2.2, marker="o", label="Deslocamento (t)")
ax_curv.set_xlabel("Calado T (m)", fontsize=8.5, fontweight="bold")
ax_curv.set_ylabel("Deslocamento (toneladas)", fontsize=8.5, fontweight="bold", color="#0284C7")
ax_curv.tick_params(axis="y", labelcolor="#0284C7")

ax_curv.axvline(0.52, color="#C4262E", lw=1.5, ls="--")
ax_curv.plot(0.52, 5.204, marker="*", markersize=12, color="#C4262E", zorder=10)
ax_curv.annotate("DWL de Projeto\nT = 0,52 m ➔ Δ = 5,20 t\n(Lwl = 7,58 m | Cb = 0,532)", 
                 xy=(0.52, 5.204), xytext=(0.46, 5.7),
                 arrowprops=dict(arrowstyle="->", color="#C4262E", lw=1.2),
                 fontsize=7.5, fontweight="bold", color="#C4262E",
                 bbox=dict(boxstyle="round,pad=0.3", facecolor="#FEF2F2", edgecolor="#FECACA"))

ax2 = ax_curv.twinx()
ax2.plot(calados_m, cbs, color="#10B981", lw=1.8, ls="--", marker="s", label="Coef. Bloco (Cb)")
ax2.plot(calados_m, cms, color="#8B5CF6", lw=1.8, ls="-.", marker="^", label="Coef. Mestra (Cm)")
ax2.set_ylabel("Coeficientes de Forma (Cb, Cm)", fontsize=8.5, fontweight="bold", color="#10B981")
ax2.tick_params(axis="y", labelcolor="#10B981")
ax2.set_ylim(0.4, 0.8)
ax_curv.grid(True, linestyle=":", alpha=0.5)

lines_1, labels_1 = ax_curv.get_legend_handles_labels()
lines_2, labels_2 = ax2.get_legend_handles_labels()
ax_curv.legend(lines_1 + lines_2, labels_1 + labels_2, loc="lower right", fontsize=7.2)

# 3. BODY PLAN
ax_body.set_title("3. SEÇÕES TRANSVERSAIS COM INDICAÇÃO DE CALADOS", fontsize=11, fontweight="bold", color="#C4262E", loc="left", pad=5)
for s in stations:
    stn = s["stn"]
    if stn <= 8:
        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 == 8 else "#2E6B72"
        lw = 2.0 if stn == 8 else 1.0
        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=6, color=color, fontweight="bold" if stn==8 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 = 1.0
        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=6, color=color)

ax_body.axhline(0.45, color="#10B981", lw=1.2, ls=":", label="Linha Leve (T=0,45m)")
ax_body.axhline(0.52, color="#0284C7", lw=2.0, ls="-.", label="Linha Projeto (T=0,52m)")
ax_body.axhline(0.60, color="#F59E0B", lw=1.2, ls="--", label="Plena Carga (T=0,60m)")

ax_body.axvline(0, color="#1F2429", lw=1.2)
ax_body.text(-0.8, 1.55, "<- POPA (B0 a B8)", fontsize=7.5, fontweight="bold", color="#2E6B72", ha="center")
ax_body.text(0.8, 1.55, "PROA (B9 a B16) ->", 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.6, 1.6)
ax_body.set_ylim(-0.1, 1.7)
ax_body.grid(True, linestyle=":", alpha=0.5)
ax_body.legend(loc="upper left", fontsize=7.2)

# 4. TABELA
ax_tab.axis("off")
ax_tab.set_title("4. MATRIZ DE CONDIÇÕES DE CARGA & CRITÉRIOS DE BORDA LIVRE", fontsize=11, fontweight="bold", color="#C4262E", loc="left", pad=5)

table_data = [
    ["Condição Operacional", "Desloc. (kg)", "Calado T (m)", "Borda Livre Meia-Nau", "Lwl (m)", "Bwl (m)", "Status"],
    ["1. Casco Leve (Lightship)", "4.082 kg", "0,45 m", "650 mm (0,65 m)", "7,36 m", "2,35 m", "Aprovado"],
    ["2. Condição Padrão SAR", "4.877 kg", "0,50 m", "600 mm (0,60 m)", "7,51 m", "2,40 m", "Operacional"],
    ["3. Projeto Carga Total (8 pess + 500L)", "5.204 kg", "0,52 m", "580 mm (0,58 m)", "7,58 m", "2,42 m", "PROJETO (DWL)"],
    ["4. Carga de Resgate Estendida", "5.873 kg", "0,56 m", "540 mm (0,54 m)", "7,70 m", "2,46 m", "Segurança Alta"],
    ["5. Sobrecarga Máxima Admissível", "6.560 kg", "0,60 m", "500 mm (0,50 m)", "7,81 m", "2,50 m", "Margem Segura"]
]

t_elem = ax_tab.table(cellText=table_data, colLabels=None, loc="upper left", bbox=[0.0, 0.45, 1.0, 0.52])
t_elem.auto_set_font_size(False)
t_elem.set_fontsize(7.2)
for (row, col), cell in t_elem.get_celld().items():
    if row == 0:
        cell.set_facecolor("#1F2429")
        cell.set_text_props(color="white", fontweight="bold")
    elif row == 3:
        cell.set_facecolor("#E0F2FE")
        cell.set_text_props(fontweight="bold", color="#0369A1")
    elif row % 2 == 1:
        cell.set_facecolor("#F8FAFC")
    cell.set_edgecolor("#CBD5E1")
    cell.set_height(0.08)

analise_text = (
    "SÍNTESE DA DEFINIÇÃO TÉCNICA (17 BALIZAS):\n"
    "• Altura Nominal de Projeto (DWL): Z = 0,52 m (520 mm) acima da Linha de Base.\n"
    "• Borda Livre na Meia-Nau (Fb): 580 mm — Excelente reserva de flutuabilidade (>190% acima da ISO 12217).\n"
    "• Borda Livre na Proa (Fb_bow): 880 mm — Proteção eficiente contra ondas e spray a 40 nós.\n"
    "• Borda Livre no Espelho (Fb_stern): 580 mm — Cockpit 100% autovaziante com drenos acima da água.\n"
    "• Calado Total com Motores Baixados: T_total ≈ 0,77 m."
)
ax_tab.text(0.0, 0.38, analise_text, va="top", ha="left", fontsize=7.2,
            bbox=dict(boxstyle="round,pad=0.5", facecolor="#F1F5F9", edgecolor="#CBD5E1", lw=1))

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, "Memória de Cálculo e Definição da Linha d'Água — 17 Balizas — Padrão Naval SI", fontsize=7.5, color="#5A626B", ha="right")

plt.savefig(pdf_path, format="pdf", dpi=300)
plt.close()
print("PDF da Linha d Agua com 17 balizas gerado com sucesso!")
