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/Gabaritos_Balizas_Planificadas_Caliandra.pdf"

# A3 Landscape (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.04, right=0.96, top=0.92, bottom=0.06)

fig.suptitle("GABARITOS DE CORTE DAS BALIZAS E CAVERNAS (FRAME TEMPLATES B1 A B19)", fontsize=15, fontweight="bold", y=0.97, color="#1F2429")
fig.text(0.5, 0.94, "Gabaritos Estruturais com 19 Balizas (Espaçamento 500,0 mm) | Projeto O RESGATE | Projetista: Caliandra | SI (mm)", 
         ha="center", fontsize=9.5, color="#5A626B", fontstyle="italic")

# Create a 4x5 grid for all 19 stations
for i in range(19):
    s = stations[i]
    stn_num = s["stn"]
    x_pos = s["x"]
    
    ax = fig.add_subplot(4, 5, i+1)
    
    y_full = [-s["sheer_hb"], -s["chine_hb"], 0.0, s["chine_hb"], s["sheer_hb"]]
    z_full = [s["sheer_ht"], s["chine_ht"], s["keel_ht"], s["chine_ht"], s["sheer_ht"]]
    
    color_frame = "#C4262E" if stn_num == 1 else ("#D97706" if stn_num == 10 else "#2E6B72")
    lw_frame = 1.8 if stn_num in [1, 10] else 1.3
    ax.plot(y_full, z_full, color=color_frame, lw=lw_frame)
    ax.fill(y_full, z_full, color="#FEF2F2" if stn_num==1 else ("#FEF3C7" if stn_num==10 else "#F0FDF4"), alpha=0.45)
    
    # Deck barrote
    ax.plot([-s["sheer_hb"], s["sheer_hb"]], [s["sheer_ht"], s["sheer_ht"]], color="#475569", lw=0.9, ls="--")
    
    # CL, BL and DWL (0.61m)
    ax.axvline(0, color="#2563EB", lw=0.5, ls=":")
    ax.axhline(0, color="#DC2626", lw=0.5, ls=":")
    ax.axhline(0.61, color="#0284C7", lw=0.5, ls="-.")
    
    boca_total = s["sheer_hb"] * 2.0 * 1000
    pontal_z   = s["sheer_ht"] * 1000
    keel_z     = s["keel_ht"] * 1000
    chine_y    = s["chine_hb"] * 1000
    chine_z    = s["chine_ht"] * 1000
    
    sub_title = f"B{stn_num} (X={int(round(x_pos*1000))}mm)"
    if stn_num == 1:
        sub_title += " [ESPELHO]"
    elif stn_num == 10:
        sub_title += " [MEIA-NAU]"
    elif stn_num == 16:
        sub_title += " [ANTEPARA]"
        
    ax.set_title(sub_title, fontsize=7.0, fontweight="bold", color=color_frame, pad=2)
    
    cota_text = (
        f"Boca: {int(round(boca_total))} mm\n"
        f"Pontal: {int(round(pontal_z))} mm\n"
        f"Quina: ({int(round(chine_y))}, {int(round(chine_z))})\n"
        f"Quilha: {int(round(keel_z))} mm | V: {s['deadrise']:.1f}°"
    )
    ax.text(0.0, 0.08, cota_text, fontsize=4.8, ha="center", va="bottom",
            bbox=dict(boxstyle="round,pad=0.15", facecolor="white", edgecolor="#CBD5E1", alpha=0.9))
    
    ax.set_xlim(-1.7, 1.7)
    ax.set_ylim(-0.1, 1.55)
    ax.grid(True, linestyle=":", alpha=0.35)
    ax.tick_params(labelsize=5.0)

fig.text(0.04, 0.02, "BRANA · Escola de Arquitetura e Engenharia Naval | Estaleiro Escola Embrião — Salvador, BA", fontsize=7.5, color="#5A626B")
fig.text(0.96, 0.02, "Prancha de Gabaritos Estruturais — 19 Balizas (B1 a B19)", fontsize=7.5, color="#5A626B", ha="right")

plt.savefig(pdf_path, format="pdf", dpi=300)
plt.close()
print("PDF dos Gabaritos atualizado!")
