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/Marcacao_Balizas_Linhas_Referencia_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.05, right=0.95, top=0.92, bottom=0.07)

# Titles
fig.suptitle("MARCAÇÃO DAS BALIZAS E LINHAS FUNDAMENTAIS DE REFERÊNCIA (21 BALIZAS)", fontsize=15, fontweight="bold", y=0.97, color="#1F2429")
fig.text(0.5, 0.94, "Linha de Base (BL), Linha de Centro (CL), Linha do Espelho e Coordenadas XYZ | Projeto O RESGATE | Projetista: Caliandra | SI", 
         ha="center", fontsize=9.5, color="#5A626B", fontstyle="italic")

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

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]

C_BL = "#C4262E"
C_CL = "#2563EB"
C_POPA = "#7C3AED"
C_POINT_SHEER = "#DC2626"
C_POINT_CHINE = "#0D9488"
C_POINT_KEEL = "#1E293B"

# 1. PERFIL: BL, POPA e PONTOS Z
ax_prof.set_title("1. ELEVAÇÃO LATERAL: LINHA DE BASE (BL), LINHA DE POPA (X=0) E PONTOS ALTURA (Z)", fontsize=10.5, fontweight="bold", color="#C4262E", loc="left", pad=4)
ax_prof.axhline(0.00, color=C_BL, lw=2.2, ls="-", label="LINHA DE BASE (BL — Z = 0,000 m)")
ax_prof.text(-0.8, 0.03, "LINHA DE BASE (BL)", color=C_BL, fontsize=8, fontweight="bold")
ax_prof.axvline(0.00, color=C_POPA, lw=2.2, ls="-", label="LINHA DE POPA (X = 0,000 m)")
ax_prof.text(0.05, 1.55, "LINHA DE POPA (X=0)", color=C_POPA, fontsize=8, fontweight="bold", rotation=90)
ax_prof.axhline(0.52, color="#0284C7", lw=1.2, ls="-.", label="Linha d'Água de Projeto (DWL = 0,520 m)")

ax_prof.plot(xs, sheer_hts, color="#E11D48", lw=1.8, label="Curva da Borda (Sheer)")
ax_prof.plot(xs, chine_hts, color="#0D9488", lw=1.5, ls="--", label="Curva da Quina (Chine)")
ax_prof.plot(xs, keel_hts, color="#1E293B", lw=1.8, label="Curva da Quilha (Keel)")

for s in stations:
    x_val = s["x"]
    stn_id = s["stn"]
    ax_prof.plot(x_val, s["keel_ht"], marker="s", markersize=3.0, color=C_POINT_KEEL)
    ax_prof.plot(x_val, s["chine_ht"], marker="o", markersize=3.0, color=C_POINT_CHINE)
    ax_prof.plot(x_val, s["sheer_ht"], marker="^", markersize=3.5, color=C_POINT_SHEER)
    ax_prof.axvline(x_val, color="#E2E8F0", lw=0.4, ls=":")
    ax_prof.text(x_val, -0.15, f"B{stn_id}", ha="center", va="top", fontsize=5.5, color="#475569")

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

# 2. PLANTA: CL, POPA e PONTOS Y
ax_plan.set_title("2. VISTA SUPERIOR: LINHA DE CENTRO (CL), LINHA DE POPA E PONTOS MEIA-BOCA (Y)", fontsize=10.5, fontweight="bold", color="#C4262E", loc="left", pad=4)
ax_plan.axhline(0.00, color=C_CL, lw=2.2, ls="-", label="LINHA DE CENTRO (CL — Y = 0,000 m)")
ax_plan.text(-0.8, 0.04, "LINHA DE CENTRO (CL)", color=C_CL, fontsize=8, fontweight="bold")
ax_plan.axvline(0.00, color=C_POPA, lw=2.2, ls="-", label="LINHA DE POPA (X = 0,000 m)")

ax_plan.plot(xs, sheer_hbs, color="#E11D48", lw=1.8, label="Meia-Boca Borda (Sheer HB)")
ax_plan.plot(xs, chine_hbs, color="#0D9488", lw=1.5, ls="--", label="Meia-Boca Quina (Chine HB)")

for s in stations:
    x_val = s["x"]
    ax_plan.plot(x_val, s["chine_hb"], marker="o", markersize=3.0, color=C_POINT_CHINE)
    ax_plan.plot(x_val, s["sheer_hb"], marker="^", markersize=3.5, color=C_POINT_SHEER)
    ax_plan.plot(x_val, 0.0, marker="s", markersize=2.5, color=C_CL)
    ax_plan.axvline(x_val, color="#E2E8F0", lw=0.4, ls=":")
    ax_plan.plot([x_val, x_val], [0, s["sheer_hb"]], color="#94A3B8", lw=0.5)

ax_plan.set_ylabel("Meia-Boca Y (m)", fontsize=8, fontweight="bold")
ax_plan.set_xlabel("Distância Longitudinal X (m) [20 intervalos espaçados a 450,0 mm]", fontsize=8, fontweight="bold")
ax_plan.set_xlim(-0.9, 9.5)
ax_plan.set_ylim(-0.15, 1.7)
ax_plan.grid(True, linestyle=":", alpha=0.5)
ax_plan.legend(loc="upper left", fontsize=7.0, ncol=3, framealpha=0.95)

# 3. BODY PLAN
ax_body.set_title("3. PLANO DE BALIZAS TRANSVERSAIS (BODY PLAN)", fontsize=10.5, fontweight="bold", color="#C4262E", loc="left", pad=4)
ax_body.axhline(0.00, color=C_BL, lw=2.0, ls="-", label="Linha de Base (BL)")
ax_body.axvline(0.00, color=C_CL, lw=2.0, ls="-", label="Linha de Centro (CL)")
ax_body.axhline(0.52, color="#0284C7", lw=1.2, ls="-.", label="DWL (Z=0,52m)")

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.plot(0.0, s["keel_ht"], marker="s", markersize=2.5, color=C_POINT_KEEL)
        ax_body.plot(-s["chine_hb"], s["chine_ht"], marker="o", markersize=3.0, color=C_POINT_CHINE)
        ax_body.plot(-s["sheer_hb"], s["sheer_ht"], marker="^", markersize=3.5, color=C_POINT_SHEER)
        ax_body.text(-s["sheer_hb"]-0.03, s["sheer_ht"], f"B{stn}", ha="right", va="center", fontsize=5.5, 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)
        ax_body.plot(0.0, s["keel_ht"], marker="s", markersize=2.5, color=C_POINT_KEEL)
        ax_body.plot(s["chine_hb"], s["chine_ht"], marker="o", markersize=3.0, color=C_POINT_CHINE)
        ax_body.plot(s["sheer_hb"], s["sheer_ht"], marker="^", markersize=3.5, color=C_POINT_SHEER)
        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.5, color=color)

ax_body.text(-0.85, 1.55, "<- POPA (B0 a B10)", fontsize=7.5, fontweight="bold", color="#2E6B72", ha="center")
ax_body.text(0.85, 1.55, "PROA (B11 a B20) ->", fontsize=7.5, fontweight="bold", color="#C4262E", ha="center")
ax_body.set_xlabel("Meia-Boca Y (m)", fontsize=8, fontweight="bold")
ax_body.set_ylabel("Altura Z (m)", fontsize=8, 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 XYZ
ax_tab.axis("off")
ax_tab.set_title("4. TABELA DE COORDENADAS PARA TRAÇADO (XYZ EM MM)", fontsize=10.5, fontweight="bold", color="#C4262E", loc="left", pad=4)

table_header = ["Stn", "X (mm)", "Quilha Z", "Quina Y", "Quina Z", "Borda Y", "Borda Z", "Deadrise"]
table_rows = []
for s in stations:
    table_rows.append([
        f"B{s['stn']}",
        f"{int(round(s['x']*1000))}",
        f"{int(round(s['keel_ht']*1000))}",
        f"{int(round(s['chine_hb']*1000))}",
        f"{int(round(s['chine_ht']*1000))}",
        f"{int(round(s['sheer_hb']*1000))}",
        f"{int(round(s['sheer_ht']*1000))}",
        f"{s['deadrise']:.1f}°"
    ])

t_grid = ax_tab.table(
    cellText=[table_header] + table_rows,
    colLabels=None,
    loc="upper left",
    bbox=[0.0, 0.02, 1.0, 0.98]
)
t_grid.auto_set_font_size(False)
t_grid.set_fontsize(5.8)

for (row, col), cell in t_grid.get_celld().items():
    if row == 0:
        cell.set_facecolor("#1F2429")
        cell.set_text_props(color="white", fontweight="bold")
    elif row == 11: # Baliza 10 (Meia-Nau)
        cell.set_facecolor("#FEF3C7")
        cell.set_text_props(fontweight="bold", color="#92400E")
    elif row == 1: # Baliza 0 (Espelho)
        cell.set_facecolor("#F3E8FF")
        cell.set_text_props(fontweight="bold", color="#6B21A8")
    elif row % 2 == 1:
        cell.set_facecolor("#F8FAFC")
    cell.set_edgecolor("#CBD5E1")
    cell.set_height(0.043)

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, "Guia Técnico de Traçado de Balizas — 21 Balizas — Padrão Naval SI (mm)", fontsize=7.5, color="#5A626B", ha="right")

plt.savefig(pdf_path, format="pdf", dpi=300)
plt.close()
print("PDF de Marcacao de Balizas com 21 balizas gerado com sucesso!")
