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

pdf_path = "/home/magdalena/eee/alunos/caliandra/Definicao_Angulo_Espelho_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)

# Main Titles
fig.suptitle("DEFINIÇÃO TÉCNICA DO ESPELHO DE POPA (TRANSOM GEOMETRY & ANGLE)", fontsize=16, fontweight="bold", y=0.97, color="#1F2429")
fig.text(0.5, 0.94, "Geometria, Inclinação (Rake Angle), Altura de Montagem e Escantilhões | Projeto O RESGATE | Projetista: Caliandra | SI", 
         ha="center", fontsize=9.5, color="#5A626B", fontstyle="italic")

# 4 Quadrants:
# Top-Left: Transom Profile (Rake Angle 14°, Trim Ranges -5° a +18°, Thrust Vector)
# Top-Right: Rear Elevation View (Vista de Ré com 2x 300 HP, Deadrise 15,3°, Eixo XL 25", Altura de Montagem)
# Bottom-Left: Diagrama de Trim Dinâmico & Comportamento Hidrodinâmico (Hole-Shot vs Planeio Livre)
# Bottom-Right: Tabela de Especificações Técnicas, Normas ABYC/ISO e Estrutura em Alumínio 5083

ax_prof = plt.subplot2grid((2, 2), (0, 0))
ax_rear = plt.subplot2grid((2, 2), (0, 1))
ax_trim = plt.subplot2grid((2, 2), (1, 0))
ax_spec = plt.subplot2grid((2, 2), (1, 1))

# Colors
C_HULL = "#2E6B72"
C_TRANSOM = "#C4262E"
C_WL = "#0284C7"
C_ENGINE = "#1F2429"
C_GRID = "#E2E8F0"

# -------------------------------------------------------------
# 1. PERFIL DO ESPELHO DE POPA (TRANSOM RAKE & TRIM GEOMETRY)
# -------------------------------------------------------------
ax_prof.set_title("1. ELEVAÇÃO LATERAL DO ESPELHO: ÂNGULO DE INCLINAÇÃO (RAKE = 14°)", fontsize=11, fontweight="bold", color="#C4262E", loc="left", pad=5)

# Coordinate origin (0,0) at bottom of keel at transom
# Transom inclination angle: 14 degrees from vertical (76 deg from horizontal)
rake_deg = 14.0
rake_rad = math.radians(rake_deg)

# Bottom of hull going forward (keel rises slightly or flat at transom)
x_fwd = np.linspace(0, 2.5, 50)
z_keel_fwd = 0.20 - 0.044 * x_fwd # Bottom line
ax_prof.plot(x_fwd, z_keel_fwd, color=C_HULL, lw=2.5, label="Fundo do Casco (Bottom)")

# Transom plate from Z=0.20 to Z=1.20 (Height = 1.00m)
z_t = np.array([0.20, 1.20])
x_t = - (z_t - 0.20) * math.tan(rake_rad)
ax_prof.plot(x_t, z_t, color=C_TRANSOM, lw=3.5, label="Espelho de Popa (Transom Plate - 14°)")

# Vertical reference line at transom bottom
ax_prof.plot([0, 0], [0.10, 1.30], color="#94A3B8", lw=1.2, ls="--", label="Linha Vertical de Referência (0°)")

# Angle arc
theta = np.linspace(math.pi/2, math.pi/2 + rake_rad, 30)
r_arc = 0.70
arc_x = - r_arc * np.sin(theta - math.pi/2)
arc_z = 0.20 + r_arc * np.cos(theta - math.pi/2)
ax_prof.plot(arc_x, arc_z, color=C_TRANSOM, lw=1.5)
ax_prof.text(-0.15, 0.65, "14,0°", color=C_TRANSOM, fontsize=9.5, fontweight="bold", ha="right")

# DWL (Linha d'água Z = 0.60 m)
ax_prof.axhline(0.60, color=C_WL, lw=1.5, ls="-.", label="DWL de Projeto (Z = 0,60 m)")

# Water shading
ax_prof.fill_between([-0.5, 2.5], -0.2, 0.60, color="#E0F2FE", alpha=0.5, zorder=0)

# Outboard Engine clamp on transom
# Engine bracket / clamp centered at Z=0.85m
bracket_poly = patches.Polygon([(-0.25, 0.70), (-0.15, 0.70), (-0.22, 0.95), (-0.32, 0.95)], facecolor="#475569", edgecolor="black", lw=1, zorder=4)
ax_prof.add_patch(bracket_poly)

# Outboard profile representation
motor_pts = [(-0.30, 0.60), (-0.65, 0.60), (-0.70, 1.25), (-0.25, 1.20)]
motor_patch = patches.Polygon(motor_pts, facecolor=C_ENGINE, edgecolor="#0F172A", lw=1.2, zorder=5)
ax_prof.add_patch(motor_patch)
ax_prof.text(-0.47, 0.90, "Motor 300 HP", color="white", fontsize=7.5, fontweight="bold", ha="center", va="center", zorder=6)

# Lower leg & Propeller line (at nominal 14° rake -> vertical thrust)
ax_prof.plot([-0.25, -0.25 - 0.75*math.tan(rake_rad)], [0.60, -0.15], color="#334155", lw=4, zorder=4)
# Propeller
ax_prof.plot([-0.25 - 0.75*math.tan(rake_rad) + 0.08], [-0.15], marker="8", markersize=9, color="#94A3B8", zorder=5)

# Thrust Vector (Empuxo Hidrodinâmico)
ax_prof.annotate("", xy=(0.40, -0.15), xytext=(-0.35, -0.15),
                 arrowprops=dict(arrowstyle="->", color="#10B981", lw=2.5))
ax_prof.text(0.45, -0.15, "Vetor de Empuxo T (Cruzeiro)\nParalelo à Linha de Base", color="#059669", fontsize=7.5, fontweight="bold", va="center")

# Annotations & Dimension lines
ax_prof.text(-0.35, 1.35, "Borda da Popa (Z = 1,20 m)\nBorda Livre = 600 mm", color="#1E293B", fontsize=7.5, fontweight="bold", ha="center")
ax_prof.text(1.2, 0.05, "Fundo em V (Deadrise 15,3°)", color=C_HULL, fontsize=7.5, fontweight="bold")

ax_prof.set_ylabel("Altura Vertical Z (m)", fontsize=8.5, fontweight="bold")
ax_prof.set_xlabel("Distância Longitudinal a Vante X (m)", fontsize=8.5, fontweight="bold")
ax_prof.set_xlim(-0.8, 2.2)
ax_prof.set_ylim(-0.3, 1.5)
ax_prof.grid(True, linestyle=":", alpha=0.5)
ax_prof.legend(loc="upper right", fontsize=7.5, framealpha=0.95)

# -------------------------------------------------------------
# 2. VISTA DE RÉ DO ESPELHO DE POPA (TRANSOM REAR VIEW)
# -------------------------------------------------------------
ax_rear.set_title("2. VISTA DE RÉ (TRANSOM ELEVATION): PARTE ESTRUTURAL & INSTALAÇÃO 2x 300 HP", fontsize=11, fontweight="bold", color="#C4262E", loc="left", pad=5)

# Transom Outline (Boca 3.00m -> Y = -1.5m to +1.5m)
# Chine at Y = +/- 1.10m, Z = 0.50m
# Keel at Y = 0.0m, Z = 0.20m
# Sheer at Y = +/- 1.50m, Z = 1.20m
y_trans = [-1.50, -1.10, 0.0, 1.10, 1.50]
z_trans = [1.20, 0.50, 0.20, 0.50, 1.20]
ax_rear.plot(y_trans, z_trans, color=C_TRANSOM, lw=2.5, label="Contorno do Espelho")
ax_rear.fill(y_trans, z_trans, color="#FEF2F2", alpha=0.7, zorder=0)

# DWL Waterline (Z = 0.60 m)
ax_rear.axhline(0.60, color=C_WL, lw=1.5, ls="-.", label="Linha d'Água (DWL = 0,60 m)")
ax_rear.fill_between([-1.6, 1.6], -0.2, 0.60, color="#E0F2FE", alpha=0.4, zorder=0)

# Deadrise Angle text
ax_rear.plot([0.0, 1.10], [0.20, 0.20], color="#94A3B8", lw=1.0, ls=":")
ax_rear.text(0.60, 0.28, "Deadrise = 15,3°", color=C_HULL, fontsize=7.5, fontweight="bold", ha="center")

# Twin Engines Mounting (Eixo Central a Y = -0.55m e Y = +0.55m, espaçamento entre eixos = 1.10m)
engine_centers = [-0.55, 0.55]
for ey, elabel in zip(engine_centers, ["Motor Bombordo (BB)\n300 HP", "Motor Boreste (BE)\n300 HP"]):
    # Motor Cowling
    m_rect = patches.FancyBboxPatch((ey-0.22, 0.65), 0.44, 0.65, boxstyle="round,pad=0.03,rounding_size=0.08", 
                                    facecolor=C_ENGINE, edgecolor="#0F172A", lw=1.2, zorder=5)
    ax_rear.add_patch(m_rect)
    ax_rear.text(ey, 0.98, elabel, color="white", fontsize=6.5, fontweight="bold", ha="center", va="center", zorder=6)
    
    # Motor Lower Unit & Propeller
    ax_rear.plot([ey, ey], [0.65, -0.15], color="#334155", lw=4, zorder=4)
    # Cavitation plate (placa anticavitação alinhada com o fundo)
    # Bottom height at Y=0.55 is Z = 0.20 + (0.55/1.10)*(0.50-0.20) = 0.35m
    z_bot = 0.20 + (abs(ey)/1.10)*0.30
    ax_rear.plot([ey-0.18, ey+0.18], [z_bot, z_bot], color="#EF4444", lw=2, zorder=6)
    ax_rear.text(ey, z_bot - 0.08, "Placa Anticavitação\n(Alinhada ao Fundo)", color="#B91C1C", fontsize=5.5, ha="center", fontweight="bold")
    
    # Propeller circle
    prop_c = patches.Circle((ey, -0.10), 0.18, facecolor="none", edgecolor="#0284C7", lw=1.5, ls="--", zorder=5)
    ax_rear.add_patch(prop_c)

# Distance between engines
ax_rear.annotate("", xy=(-0.55, 1.35), xytext=(0.55, 1.35),
                 arrowprops=dict(arrowstyle="<->", color="#1F2429", lw=1.2))
ax_rear.text(0.0, 1.39, "Espaçamento Entre Eixos = 1.100 mm (1,10 m)", fontsize=7.5, fontweight="bold", ha="center")

# Total Beam cota
ax_rear.annotate("", xy=(-1.50, -0.25), xytext=(1.50, -0.25),
                 arrowprops=dict(arrowstyle="<->", color="#1F2429", lw=1.2))
ax_rear.text(0.0, -0.32, "Boca Total no Espelho = 3.000 mm (3,00 m)", fontsize=8, fontweight="bold", ha="center")

# Shaft length annotation (Altura do Espelho para Eixo Extra-Longo 25" / 635 mm)
ax_rear.text(1.25, 0.85, "Altura de Montagem:\nEixo XL = 25\" (635 mm)\nNorma ABYC S-30", fontsize=7, color="#0369A1", fontweight="bold",
             bbox=dict(boxstyle="round,pad=0.3", facecolor="#F0F9FF", edgecolor="#BAE6FD"))

ax_rear.set_xlabel("Meia-Boca Transversal Y (m)", fontsize=8.5, fontweight="bold")
ax_rear.set_ylabel("Altura Vertical Z (m)", fontsize=8.5, fontweight="bold")
ax_rear.set_xlim(-1.8, 1.8)
ax_rear.set_ylim(-0.35, 1.55)
ax_rear.grid(True, linestyle=":", alpha=0.5)
ax_rear.legend(loc="upper left", fontsize=7.5)

# -------------------------------------------------------------
# 3. DIAGRAMA DE TRIM & COMPORTAMENTO HIDRODINÂMICO
# -------------------------------------------------------------
ax_trim.set_title("3. DINÂMICA DE EMPUXO E FAIXAS DE TRIM ATIVO (POWER TRIM)", fontsize=11, fontweight="bold", color="#C4262E", loc="left", pad=5)

# Illustrate the 3 Trim Ranges: Negative (-5°), Neutral (0° / 14° Rake), Positive (+15°)
trim_modes = [
    ("A. Trim Negativo (-5°)", -5.0, "#EF4444", 0.5, "Arrancada / Hole-Shot:\n• Abaixa a proa\n• Transição rápida ao planeio\n• Impede empinamento com carga"),
    ("B. Trim Neutro (0° / Rake 14°)", 0.0, "#10B981", 1.5, "Cruzeiro Eficiente (30 nós):\n• Empuxo horizontal perfeito\n• Mínimo arrasto e consumo\n• Estabilidade direcional plena"),
    ("C. Trim Positivo (+15°)", 15.0, "#3B82F6", 2.5, "Velocidade Máxima (40 nós):\n• Levanta a proa\n• Reduz área molhada\n• Máxima velocidade de interceptação")
]

for label, angle_offset, col, x_pos, desc in trim_modes:
    # Mini hull profile
    base_x = x_pos
    ax_trim.plot([base_x-0.4, base_x+0.3], [1.2, 1.2], color=C_HULL, lw=2)
    # Transom line
    ax_trim.plot([base_x-0.4, base_x-0.4-0.4*math.tan(math.radians(14))], [1.2, 0.6], color=C_TRANSOM, lw=2.5)
    
    # Engine leg with angle
    eff_angle = 14.0 + angle_offset
    rad = math.radians(eff_angle)
    leg_x = [base_x-0.4-0.2*math.tan(math.radians(14)), base_x-0.4-0.2*math.tan(math.radians(14)) - 0.6*math.tan(rad)]
    leg_z = [0.9, 0.3]
    ax_trim.plot(leg_x, leg_z, color=col, lw=3.5)
    
    # Thrust vector arrow
    thrust_dx = 0.35 * math.cos(rad)
    thrust_dz = 0.35 * math.sin(rad)
    ax_trim.annotate("", xy=(leg_x[1] + thrust_dx, leg_z[1] + thrust_dz), xytext=(leg_x[1], leg_z[1]),
                     arrowprops=dict(arrowstyle="->", color=col, lw=2))
    
    ax_trim.text(base_x, 1.35, label, color=col, fontsize=8, fontweight="bold", ha="center")
    ax_trim.text(base_x, 0.15, desc, color="#1E293B", fontsize=6.8, ha="center", va="top",
                 bbox=dict(boxstyle="round,pad=0.3", facecolor="#F8FAFC", edgecolor=C_GRID))

ax_trim.set_xlim(0.0, 3.0)
ax_trim.set_ylim(-0.4, 1.5)
ax_trim.axis("off")

# -------------------------------------------------------------
# 4. TABELA DE ESPECIFICAÇÕES, NORMAS E ESTRUTURA 5083
# -------------------------------------------------------------
ax_spec.axis("off")
ax_spec.set_title("4. ESPECIFICAÇÃO DE PROJETO DO ESPELHO DE POPA", fontsize=11, fontweight="bold", color="#C4262E", loc="left", pad=5)

spec_data = [
    ["Parâmetro de Engenharia", "Valor de Projeto", "Fundamentação Técnica / Norma"]
]

linhas_spec = [
    ["Ângulo de Inclinação (Rake)", "14,0° (76,0° da base)", "Padrão ABYC S-30 / ISO 15084 para motores de popa de alta potência."],
    ["Potência Admissível no Espelho", "600 HP (2x 300 HP)", "Dimensionado para suportar empuxo estático de 2.200 kgf e torque dinâmico."],
    ["Altura de Montagem (Transom Height)", "635 mm (25\" - Eixo XL)", "Compatível com a linha profissional Mercury Verado / Yamaha V6 300."],
    ["Espaçamento entre Centros de Eixos", "1.100 mm (1,10 m)", "Garante fluxo de água limpo sem interferência entre hélices e rabetas."],
    ["Deadrise no Espelho de Popa", "15,3° no fundo", "Compromisso ideal entre sustentação no planeio e maciez de impacto."],
    ["Espessura da Chapa do Espelho", "6,0 mm a 8,0 mm", "Alumínio Naval 5083-H116 soldado com reforçadores de canto."],
    ["Reforço Estrutural (Transom Knees)", "3x Sicordas Triangulares 8mm", "Transfere o empuxo diretamente para as longarinas de fundo do casco."],
    ["Drenagem do Cockpit (Scuppers)", "2x Válvulas Flapper Ø 75mm", "Drenagem 100% autovaziante por gravidade, 150 mm acima da DWL."]
]

for r in linhas_spec:
    spec_data.append(r)

table_s = ax_spec.table(
    cellText=spec_data,
    colLabels=None,
    loc="upper left",
    bbox=[0.0, 0.25, 1.0, 0.72]
)
table_s.auto_set_font_size(False)
table_s.set_fontsize(7.2)

for (row, col), cell in table_s.get_celld().items():
    if row == 0:
        cell.set_facecolor("#1F2429")
        cell.set_text_props(color="white", fontweight="bold")
    elif row == 1:
        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)

# Quadro de Conclusão Técnica
conclusao_txt = (
    "CONCLUSÃO DE PROJETO (JUSTIFICATIVA DO ÂNGULO DE 14°):\n"
    "O ângulo de 14° é o padrão de excelência para lanchas de intervenção rápida. Ele posiciona os motores em atitude\n"
    "neutra paralela à quilha em cruzeiro (30 nós), permite curso de -5° para aceleração sem cavitação no arranque (hole-shot)\n"
    "e fornece até +15° de trim positivo para atingir a velocidade máxima de 40 nós com arrasto mínimo."
)
ax_spec.text(0.0, 0.18, conclusao_txt, va="top", ha="left", fontsize=7.2,
             bbox=dict(boxstyle="round,pad=0.5", facecolor="#FEF3C7", edgecolor="#F59E0B", 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 Técnica de Geometria do Espelho de Popa — Documento Oficial de Projeto", fontsize=7.5, color="#5A626B", ha="right")

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