import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from reportlab.lib.pagesizes import A4, landscape
from reportlab.lib import colors
from reportlab.lib.units import cm, mm
from reportlab.platypus import (
    SimpleDocTemplate, Paragraph, Spacer, Image, Table, TableStyle, PageBreak, KeepTogether, HRFlowable
)
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_JUSTIFY, TA_RIGHT

# 1. Gerar imagem das 10 tiras em escala 1:75 sobre malha
# Na escala 1:75:
# 1 metro real (1000 mm) = 1000 / 75 = 13.33 mm no papel.
# Um quadrado da malha de 1000 mm real -> 13.33 mm no papel.
# Um quadrado da malha de 500 mm real -> 6.67 mm no papel.

# Dados das 10 tiras:
tiras_data = [
    ("Tira 1", 15.365, 0.359, 4.209),
    ("Tira 2", 15.374, 0.427, 4.208),
    ("Tira 3", 15.392, 0.475, 4.210),
    ("Tira 4", 15.418, 0.527, 4.216),
    ("Tira 5", 15.448, 0.529, 4.225),
    ("Tira 6", 15.478, 0.487, 4.233),
    ("Tira 7", 15.501, 0.440, 4.239),
    ("Tira 8", 15.514, 0.378, 4.243),
    ("Tira 9", 15.515, 0.326, 4.247),
    ("Tira 10", 15.512, 0.327, 4.252)
]

# Gerar gráfico das 10 tiras planificadas (Landscape)
fig, ax = plt.subplots(figsize=(11.69, 7.5), dpi=200) # Proporção A4 paisagem
fig.patch.set_facecolor('white')
ax.set_facecolor('#FCFCFC')

# Título do desenho
ax.set_title("PLANO DE CORTE DAS CHAPAS PLANIFICADAS (10 TIRAS) — ESCALA 1:75\nBarco-Escola das Águas (LOA 15,00 m) · Projetista: Luciano Mandú", fontsize=11, fontweight='bold', color='#2E1A11', pad=12)

# Desenhar as 10 tiras dispostas verticalmente
y_offset = 0
for idx, (nome, comp, larg, area) in enumerate(tiras_data):
    # Forma representativa de tira de casco desenvolvida
    x_pts = np.linspace(0, comp, 100)
    # Largura variável ao longo da tira (mais estreita nas pontas, bojo no centro)
    w = larg * (1 - 0.35 * ((x_pts - comp/2)/(comp/2))**2)
    
    y_center = y_offset + larg/2
    y_sup = y_center + w/2
    y_inf = y_center - w/2
    
    # Preencher a chapa
    ax.fill_between(x_pts, y_inf, y_sup, color='#D7CCC8', edgecolor='#4E342E', lw=1.2, alpha=0.85)
    
    # Linha de centro da tira
    ax.plot([0, comp], [y_center, y_center], color='#8D6E63', linestyle=':', lw=0.8)
    
    # Texto identificador da chapa
    ax.text(comp/2, y_center, f"{nome}: {comp:.3f} m x {larg:.3f} m ({comp/75*1000:.1f} mm x {larg/75*1000:.1f} mm no papel)", 
            ha='center', va='center', fontsize=7, fontweight='bold', color='#27160F',
            bbox=dict(boxstyle="round,pad=0.2", fc="white", ec="#8D6E63", alpha=0.9))
    
    y_offset += larg + 0.35 # Espaçamento entre tiras

# Malha de referência de 1,0 m (1000 mm)
ax.set_xticks(np.arange(0, 17, 1.0))
ax.set_yticks(np.arange(0, y_offset + 0.5, 1.0))
ax.grid(True, which='both', color='#B0BEC5', linestyle='--', linewidth=0.6, alpha=0.7)

ax.set_xlim(-0.8, 16.5)
ax.set_ylim(-0.5, y_offset)
ax.set_xlabel("Comprimento Real (m) [Na escala 1:75: 1 metro = 13,33 mm no papel]", fontsize=9, fontweight='bold')
ax.set_ylabel("Largura Acumulada (m)", fontsize=9, fontweight='bold')

# Barra de escala gráfica oficial 1:75
# No papel: 5 metros reais = 5000 mm / 75 = 66.67 mm
scale_box = patches.Rectangle((0, y_offset - 0.6), 5.0, 0.4, facecolor='#EFEBE9', edgecolor='#3E2723', lw=1)
ax.add_patch(scale_box)
ax.text(2.5, y_offset - 0.4, "ESCALA GRÁFICA 1:75\n5,0 m reais = 66,7 mm no papel", ha='center', va='center', fontsize=7.5, fontweight='bold', color='#3E2723')

plt.tight_layout()
img_tiras_path = "/home/magdalena/eee/alunos/luciano-mandu/chapas_planificadas_escala_1_75.png"
plt.savefig(img_tiras_path, dpi=200)
plt.close()

# 2. Gerar gráfico dos 5 Gabaritos de Baliza em Escala 1:75
fig_g, ax_g = plt.subplots(figsize=(11.69, 7.5), dpi=200)
fig_g.patch.set_facecolor('white')
ax_g.set_facecolor('#FCFCFC')

ax_g.set_title("GABARITOS DE BALIZAS / CAVERNAS (ESCALA 1:75)\nBarco-Escola das Águas · Balizas 1 a 5", fontsize=11, fontweight='bold', color='#2E1A11', pad=12)

balizas_info = [
    ("Baliza 1 (x=0 m - Ré)", 4.300, 1.700, 0.416, 2.5),
    ("Baliza 2 (x=3 m)", 4.450, 1.700, 0.160, 8.5),
    ("Baliza 3 (x=6 m - Mestra)", 4.500, 1.700, 0.054, 14.5),
    ("Baliza 4 (x=9 m)", 4.332, 1.700, 0.100, 20.5),
    ("Baliza 5 (x=12 m - Vante)", 3.388, 1.700, 0.565, 26.0)
]

for nome_b, boca_b, alt_b, kq, x_pos in balizas_info:
    # Curva da baliza
    mb = boca_b / 2.0
    y_half = np.linspace(-mb, mb, 60)
    z_curve = kq + (alt_b - kq) * (np.abs(y_half) / mb)**1.3
    
    # Desenhar contorno da baliza
    ax_g.plot(y_half + x_pos, z_curve, color='#3E2723', lw=2)
    # Fechar linha de convés
    ax_g.plot([-mb + x_pos, mb + x_pos], [alt_b, alt_b], color='#5D4037', lw=1.5, linestyle='--')
    # Preencher interior
    ax_g.fill_between(y_half + x_pos, z_curve, alt_b, color='#E0D7D3', alpha=0.45)
    
    # Eixo de centro
    ax_g.plot([x_pos, x_pos], [0, alt_b + 0.2], color='#C62828', linestyle=':', lw=1)
    
    # Texto
    ax_g.text(x_pos, alt_b + 0.35, f"{nome_b}\nB={boca_b:.2f}m ({boca_b/75*1000:.1f} mm)\nH={alt_b:.2f}m ({alt_b/75*1000:.1f} mm)",
              ha='center', va='bottom', fontsize=7, fontweight='bold', color='#27160F')

ax_g.set_xlim(-1.0, 29.5)
ax_g.set_ylim(-0.2, 2.8)
ax_g.set_xlabel("Disposição dos Gabaritos na Folha A4", fontsize=9, fontweight='bold')
ax_g.set_ylabel("Altura Acima da Linha de Base (m)", fontsize=9, fontweight='bold')
ax_g.grid(True, linestyle='--', alpha=0.5)

plt.tight_layout()
img_gabaritos_path = "/home/magdalena/eee/alunos/luciano-mandu/gabaritos_balizas_escala_1_75.png"
plt.savefig(img_gabaritos_path, dpi=200)
plt.close()

# 3. Gerar o PDF Oficial em Formato A4
pdf_path_escala = "/home/magdalena/eee/alunos/luciano-mandu/Planificacao_Casco_Escala_1_75_Luciano_Mandu.pdf"

doc = SimpleDocTemplate(
    pdf_path_escala,
    pagesize=landscape(A4),
    leftMargin=1.2*cm,
    rightMargin=1.2*cm,
    topMargin=1.0*cm,
    bottomMargin=1.0*cm
)

styles = getSampleStyleSheet()

primary_color = colors.HexColor("#3E2723")
secondary_color = colors.HexColor("#5D4037")

t_style = ParagraphStyle('TStyle', parent=styles['Heading1'], fontName='Helvetica-Bold', fontSize=15, leading=18, alignment=TA_CENTER, textColor=primary_color)
sub_style = ParagraphStyle('SubStyle', parent=styles['Normal'], fontName='Helvetica', fontSize=9, leading=12, alignment=TA_CENTER, textColor=secondary_color)
h2_style = ParagraphStyle('H2Style', parent=styles['Heading2'], fontName='Helvetica-Bold', fontSize=11, leading=14, textColor=primary_color, spaceBefore=4, spaceAfter=3)
body_style = ParagraphStyle('BodyStyle', parent=styles['Normal'], fontName='Helvetica', fontSize=8, leading=11, alignment=TA_JUSTIFY, textColor=colors.HexColor("#212121"))
th_style = ParagraphStyle('TH', parent=styles['Normal'], fontName='Helvetica-Bold', fontSize=7.5, leading=9, textColor=colors.white, alignment=TA_CENTER)
tc_style = ParagraphStyle('TC', parent=styles['Normal'], fontName='Helvetica', fontSize=7, leading=9, alignment=TA_CENTER, textColor=colors.HexColor("#212121"))

story = []

# PÁGINA 1: Apresentação e Tabela de Conversão para Escala 1:75
story.append(Paragraph("PLANIFICAÇÃO DE CASCO EM ESCALA 1:75 (FORMATO A4)", t_style))
story.append(Paragraph("<b>Barco-Escola das Águas</b> · Comprimento: 15,00 m · Boca: 4,50 m · Pontal: 1,70 m<br/><b>Aluno/Projetista:</b> Luciano Mandú | <b>Instituição:</b> Brana / Estaleiro Escola Embrião", sub_style))
story.append(Spacer(1, 4))
story.append(HRFlowable(width="100%", thickness=1, color=primary_color, spaceAfter=6))

story.append(Paragraph("<b>1. REGRA PRÁTICA DE CONVERSÃO PARA IMPRESSÃO EM A4 (ESCALA 1:75)</b>", h2_style))
story.append(Paragraph(
    "A folha A4 em modo Paisagem mede <b>297 mm de largura por 210 mm de altura</b> (área útil de ~275 mm x 190 mm). Na <b>escala 1:75</b>, o barco de 15,51 m de chapa desenvolvida cabe com folga ocupando <b>206,9 mm</b> no papel. Cada <b>1,0 metro real</b> equivale a exatamente <b>13,33 mm</b> no papel (1 cm no papel = 0,75 m na realidade).",
    body_style
))
story.append(Spacer(1, 4))

# Tabela das 10 tiras com dimensões no papel
table_tiras_data = [
    [Paragraph("Identificação", th_style), Paragraph("Dimensão Real (m)", th_style), Paragraph("Dimensão no Papel A4 (Escala 1:75)", th_style), Paragraph("Área Plana", th_style), Paragraph("Deformação", th_style)],
    [Paragraph("Tira 1", tc_style), Paragraph("15,365 m x 0,359 m", tc_style), Paragraph("<b>204,9 mm x 4,8 mm</b> (20,5 cm x 0,5 cm)", tc_style), Paragraph("4,209 m²", tc_style), Paragraph("Exata", tc_style)],
    [Paragraph("Tira 2", tc_style), Paragraph("15,374 m x 0,427 m", tc_style), Paragraph("<b>205,0 mm x 5,7 mm</b> (20,5 cm x 0,6 cm)", tc_style), Paragraph("4,208 m²", tc_style), Paragraph("0,001 %", tc_style)],
    [Paragraph("Tira 3", tc_style), Paragraph("15,392 m x 0,475 m", tc_style), Paragraph("<b>205,2 mm x 6,3 mm</b> (20,5 cm x 0,6 cm)", tc_style), Paragraph("4,210 m²", tc_style), Paragraph("0,004 %", tc_style)],
    [Paragraph("Tira 4", tc_style), Paragraph("15,418 m x 0,527 m", tc_style), Paragraph("<b>205,6 mm x 7,0 mm</b> (20,6 cm x 0,7 cm)", tc_style), Paragraph("4,216 m²", tc_style), Paragraph("0,010 %", tc_style)],
    [Paragraph("Tira 5", tc_style), Paragraph("15,448 m x 0,529 m", tc_style), Paragraph("<b>206,0 mm x 7,1 mm</b> (20,6 cm x 0,7 cm)", tc_style), Paragraph("4,225 m²", tc_style), Paragraph("0,017 %", tc_style)],
    [Paragraph("Tira 6", tc_style), Paragraph("15,478 m x 0,487 m", tc_style), Paragraph("<b>206,4 mm x 6,5 mm</b> (20,6 cm x 0,7 cm)", tc_style), Paragraph("4,233 m²", tc_style), Paragraph("0,021 %", tc_style)],
    [Paragraph("Tira 7", tc_style), Paragraph("15,501 m x 0,440 m", tc_style), Paragraph("<b>206,7 mm x 5,9 mm</b> (20,7 cm x 0,6 cm)", tc_style), Paragraph("4,239 m²", tc_style), Paragraph("0,020 %", tc_style)],
    [Paragraph("Tira 8", tc_style), Paragraph("15,514 m x 0,378 m", tc_style), Paragraph("<b>206,9 mm x 5,0 mm</b> (20,7 cm x 0,5 cm)", tc_style), Paragraph("4,243 m²", tc_style), Paragraph("0,012 %", tc_style)],
    [Paragraph("Tira 9", tc_style), Paragraph("15,515 m x 0,326 m", tc_style), Paragraph("<b>206,9 mm x 4,3 mm</b> (20,7 cm x 0,4 cm)", tc_style), Paragraph("4,247 m²", tc_style), Paragraph("0,004 %", tc_style)],
    [Paragraph("Tira 10", tc_style), Paragraph("15,512 m x 0,327 m", tc_style), Paragraph("<b>206,8 mm x 4,4 mm</b> (20,7 cm x 0,4 cm)", tc_style), Paragraph("4,252 m²", tc_style), Paragraph("Exata", tc_style)],
]

t1 = Table(table_tiras_data, colWidths=[2.5*cm, 4.5*cm, 7.5*cm, 2.5*cm, 2.5*cm])
t1.setStyle(TableStyle([
    ('BACKGROUND', (0,0), (-1,0), primary_color),
    ('GRID', (0,0), (-1,-1), 0.5, colors.HexColor("#BDBDBD")),
    ('ROWBACKGROUNDS', (0,1), (-1,-1), [colors.HexColor("#FAFAFA"), colors.HexColor("#EEEEEE")]),
    ('TOPPADDING', (0,0), (-1,-1), 2),
    ('BOTTOMPADDING', (0,0), (-1,-1), 2),
]))
story.append(t1)
story.append(Spacer(1, 6))

story.append(Paragraph("<b>2. GABARITOS DAS BALIZAS NO PAPEL A4 (ESCALA 1:75)</b>", h2_style))
table_bal_data = [
    [Paragraph("Baliza", th_style), Paragraph("Posição x da Popa", th_style), Paragraph("Boca Real / Papel (1:75)", th_style), Paragraph("Altura Real / Papel (1:75)", th_style)],
    [Paragraph("Baliza 1", tc_style), Paragraph("x = 0 mm (0,0 mm no papel)", tc_style), Paragraph("4.300 mm → <b>57,3 mm</b> (5,7 cm)", tc_style), Paragraph("1.700 mm → <b>22,7 mm</b> (2,3 cm)", tc_style)],
    [Paragraph("Baliza 2", tc_style), Paragraph("x = 3.000 mm (40,0 mm no papel)", tc_style), Paragraph("4.450 mm → <b>59,3 mm</b> (5,9 cm)", tc_style), Paragraph("1.700 mm → <b>22,7 mm</b> (2,3 cm)", tc_style)],
    [Paragraph("Baliza 3 (Mestra)", tc_style), Paragraph("x = 6.000 mm (80,0 mm no papel)", tc_style), Paragraph("4.500 mm → <b>60,0 mm</b> (6,0 cm)", tc_style), Paragraph("1.700 mm → <b>22,7 mm</b> (2,3 cm)", tc_style)],
    [Paragraph("Baliza 4", tc_style), Paragraph("x = 9.000 mm (120,0 mm no papel)", tc_style), Paragraph("4.332 mm → <b>57,8 mm</b> (5,8 cm)", tc_style), Paragraph("1.700 mm → <b>22,7 mm</b> (2,3 cm)", tc_style)],
    [Paragraph("Baliza 5", tc_style), Paragraph("x = 12.000 mm (160,0 mm no papel)", tc_style), Paragraph("3.388 mm → <b>45,2 mm</b> (4,5 cm)", tc_style), Paragraph("1.700 mm → <b>22,7 mm</b> (2,3 cm)", tc_style)],
]
t2 = Table(table_bal_data, colWidths=[3.0*cm, 5.5*cm, 5.5*cm, 5.5*cm])
t2.setStyle(TableStyle([
    ('BACKGROUND', (0,0), (-1,0), secondary_color),
    ('GRID', (0,0), (-1,-1), 0.5, colors.HexColor("#BDBDBD")),
    ('ROWBACKGROUNDS', (0,1), (-1,-1), [colors.HexColor("#FAFAFA"), colors.HexColor("#EEEEEE")]),
    ('TOPPADDING', (0,0), (-1,-1), 2),
    ('BOTTOMPADDING', (0,0), (-1,-1), 2),
]))
story.append(t2)

story.append(PageBreak())

# PÁGINA 2: Desenho das 10 Chapas em Escala 1:75
story.append(Paragraph("3. DESENHO TÉCNICO DAS 10 CHAPAS DESENVOLVIDAS (ESCALA 1:75)", h2_style))
if os.path.exists(img_tiras_path):
    story.append(Image(img_tiras_path, width=26.5*cm, height=15.5*cm))

story.append(PageBreak())

# PÁGINA 3: Desenho dos Gabaritos das Balizas em Escala 1:75
story.append(Paragraph("4. DESENHO TÉCNICO DOS GABARITOS DE BALIZAS (ESCALA 1:75)", h2_style))
if os.path.exists(img_gabaritos_path):
    story.append(Image(img_gabaritos_path, width=26.5*cm, height=15.5*cm))

doc.build(story)
print(f"PDF de planificação em escala 1:75 gerado com sucesso em: {pdf_path_escala}")
