import os
from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.units import cm
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

pdf_path = "/home/magdalena/eee/alunos/luciano-mandu/Projeto_Barco_Escola_das_Aguas_Luciano_Mandu.pdf"

doc = SimpleDocTemplate(
    pdf_path,
    pagesize=A4,
    leftMargin=1.5*cm,
    rightMargin=1.5*cm,
    topMargin=1.5*cm,
    bottomMargin=1.5*cm
)

styles = getSampleStyleSheet()

# Custom styles
primary_color = colors.HexColor("#3E2723")   # Marrom escuro náutico/madeira
secondary_color = colors.HexColor("#8D6E63") # Marrom médio
accent_color = colors.HexColor("#0D47A1")    # Azul marinho
bg_box = colors.HexColor("#EFEBE9")

title_style = ParagraphStyle(
    'DocTitle',
    parent=styles['Heading1'],
    fontName='Helvetica-Bold',
    fontSize=20,
    leading=24,
    alignment=TA_CENTER,
    textColor=primary_color
)

subtitle_style = ParagraphStyle(
    'DocSubTitle',
    parent=styles['Normal'],
    fontName='Helvetica',
    fontSize=11,
    leading=15,
    alignment=TA_CENTER,
    textColor=secondary_color
)

h1_style = ParagraphStyle(
    'SectionH1',
    parent=styles['Heading2'],
    fontName='Helvetica-Bold',
    fontSize=13,
    leading=16,
    textColor=primary_color,
    spaceBefore=8,
    spaceAfter=4
)

body_style = ParagraphStyle(
    'BodyTextCustom',
    parent=styles['Normal'],
    fontName='Helvetica',
    fontSize=9.5,
    leading=13.5,
    alignment=TA_JUSTIFY,
    textColor=colors.HexColor("#212121")
)

bullet_style = ParagraphStyle(
    'BulletCustom',
    parent=styles['Normal'],
    fontName='Helvetica',
    fontSize=9,
    leading=13,
    textColor=colors.HexColor("#212121"),
    leftIndent=12
)

table_header_style = ParagraphStyle(
    'THStyle',
    parent=styles['Normal'],
    fontName='Helvetica-Bold',
    fontSize=9,
    leading=11,
    textColor=colors.white,
    alignment=TA_CENTER
)

table_cell_style = ParagraphStyle(
    'TCStyle',
    parent=styles['Normal'],
    fontName='Helvetica',
    fontSize=8.5,
    leading=11,
    textColor=colors.HexColor("#212121")
)

table_cell_center = ParagraphStyle(
    'TCCenter',
    parent=styles['Normal'],
    fontName='Helvetica-Bold',
    fontSize=8.5,
    leading=11,
    alignment=TA_CENTER,
    textColor=colors.HexColor("#212121")
)

story = []

# Cabeçalho / Título
story.append(Paragraph("PROJETO CONCEITUAL: BARCO-ESCOLA DAS ÁGUAS", title_style))
story.append(Spacer(1, 3))
story.append(Paragraph("Embarcação Tradicional Híbrida (Canoa Tupinambá + Saveiro da Bahia)<br/><b>Aluno:</b> Luciano Mandú | <b>Instituição:</b> Brana / Estaleiro Escola Embrião (EEE)", subtitle_style))
story.append(Spacer(1, 6))
story.append(HRFlowable(width="100%", thickness=1.5, color=primary_color, spaceAfter=8))

# 1. Resumo Executivo e Caso de Uso
story.append(Paragraph("1. DECLARAÇÃO DE MISSÃO E CASO DE USO", h1_style))
story.append(Paragraph(
    "O projeto <b>Escola das Águas</b> nasce da integração cultural e tecnológica entre as linhas afiladas das canoas a remo tradicionais indígenas Tupinambá e a robustez e maestria dos saveiros de vela de içar da Bahia. A embarcação desempenha papel fundamental na soberania educacional e mobilidade ribeirinha no Recôncavo e Baixo Sul baiano.",
    body_style
))
story.append(Spacer(1, 4))

story.append(Paragraph("• <b>Missão Principal (75% do tempo):</b> Transporte comunitário e escolar regular de até <b>50 passageiros</b> (crianças, professores e tripulação) entre comunidades de manguezal, ilhas e sedes escolares.", bullet_style))
story.append(Paragraph("• <b>Missão Secundária (25% do tempo):</b> Barco-escola itinerante e laboratório de vivência ecológica para <b>20 a 25 pessoas</b> com pernoite em redes e bancadas didáticas.", bullet_style))
story.append(Paragraph("• <b>Área de Navegação:</b> Baía de Todos os Santos (BTS), Contracosta de Itaparica, rios Paraguaçu, Jaguaripe, Una, Rio do Inferno (Tinharé/Boipeba), Rio Joanes e passagens em mar aberto costeiro até Cairu e Camamu.", bullet_style))
story.append(Spacer(1, 8))

# 2. Dimensões e Hidrostática
story.append(Paragraph("2. DIMENSÕES PRINCIPAIS E RESULTADOS HIDROSTÁTICOS", h1_style))

t_data = [
    [Paragraph("Parâmetro de Projeto", table_header_style), Paragraph("Símbolo", table_header_style), Paragraph("Valor / Unidade", table_header_style), Paragraph("Significado Técnico / Aplicação", table_header_style)],
    [Paragraph("Comprimento Total", table_cell_style), Paragraph("LOA", table_cell_center), Paragraph("15,00 m", table_cell_center), Paragraph("Porte dos grandes saveiros da Bahia (~50 pés)", table_cell_style)],
    [Paragraph("Comprimento de Linha d'Água", table_cell_style), Paragraph("LWL", table_cell_center), Paragraph("13,80 m", table_cell_center), Paragraph("Base para velocidade crítica de casco (8,8 nós)", table_cell_style)],
    [Paragraph("Boca Máxima Moldada", table_cell_style), Paragraph("B", table_cell_center), Paragraph("4,50 m", table_cell_center), Paragraph("Estabilidade de forma excepcional para transporte", table_cell_style)],
    [Paragraph("Pontal Moldado", table_cell_style), Paragraph("D", table_cell_center), Paragraph("1,70 m", table_cell_center), Paragraph("Garante borda livre segura em mar aberto", table_cell_style)],
    [Paragraph("Calado de Projeto", table_cell_style), Paragraph("T", table_cell_center), Paragraph("0,95 m", table_cell_center), Paragraph("Permite entrar em rios rasos e esteiros de maré", table_cell_style)],
    [Paragraph("Borda Livre a Meia-Nau", table_cell_style), Paragraph("Fb", table_cell_center), Paragraph("0,75 m", table_cell_center), Paragraph("Excelente reserva de flutuabilidade contra ondas", table_cell_style)],
    [Paragraph("Deslocamento Máximo", table_cell_style), Paragraph("Δ", table_cell_center), Paragraph("25,13 t", table_cell_center), Paragraph("Casco madeira + 3t lastro + 50 pessoas + carga", table_cell_style)],
    [Paragraph("Imersão por Centímetro", table_cell_style), Paragraph("TPC", table_cell_center), Paragraph("0,427 t/cm", table_cell_center), Paragraph("A cada 427 kg embarcados, o calado sobe só 1 cm", table_cell_style)],
    [Paragraph("Altura Metacêntrica Inicial", table_cell_style), Paragraph("GMt", table_cell_center), Paragraph("1,74 m", table_cell_center), Paragraph("Segurança total: banda < 5° mesmo com todos no bordo", table_cell_style)],
]

t = Table(t_data, colWidths=[4.2*cm, 1.8*cm, 2.5*cm, 7.5*cm])
t.setStyle(TableStyle([
    ('BACKGROUND', (0,0), (-1,0), primary_color),
    ('ALIGN', (0,0), (-1,-1), 'LEFT'),
    ('VALIGN', (0,0), (-1,-1), 'MIDDLE'),
    ('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), 3),
    ('BOTTOMPADDING', (0,0), (-1,-1), 3),
]))
story.append(t)
story.append(Spacer(1, 8))

# 3. Desenho Conceitual do Barco
story.append(Paragraph("3. DESENHO CONCEITUAL: PERFIL E PLANTA DO CONVÉS", h1_style))
img_path_desenho = "/home/magdalena/eee/alunos/luciano-mandu/desenho_conceitual_barco_escola.png"
if os.path.exists(img_path_desenho):
    story.append(Image(img_path_desenho, width=16.5*cm, height=11.5*cm))
story.append(Spacer(1, 6))

story.append(PageBreak())

# Página 2: Seções Transversais e Especificações Construtivas
story.append(Paragraph("4. PLANO DE BALIZAS / SEÇÕES TRANSVERSAIS (BODY PLAN)", h1_style))
story.append(Paragraph(
    "As seções transversais demonstram a fusão harmônica entre a hidrodinâmica das canoas a remo Tupinambá na proa (seções finas em 'V' para cortar ondas) e a geometria do saveiro baiano a meia-nau e ré (fundo chato com bojo arredondado e quilha corrida para estabilidade e baixo calado).",
    body_style
))
story.append(Spacer(1, 4))

img_path_body = "/home/magdalena/eee/alunos/luciano-mandu/body_plan_secoes.png"
if os.path.exists(img_path_body):
    story.append(Image(img_path_body, width=16.0*cm, height=9.2*cm))
story.append(Spacer(1, 8))

# 5. Arranjo e Especificações Construtivas
story.append(Paragraph("5. ARRANJO ESPACIAL, ESTRUTURA E SUSTENTABILIDADE", h1_style))

story.append(Paragraph("• <b>Material Construtivo:</b> Madeira tradicional regional com cavername maciço e tábuas pregadas/rebitadas (carpintaria naval do Estaleiro Escola Embrião).", bullet_style))
story.append(Paragraph("• <b>Convés Aberto e Conforto Térmico:</b> Convés corrido sombreado por esteios de madeira e cobertura de palha trançada tradicional, proporcionando ventilação permanente sem acúmulo de calor.", bullet_style))
story.append(Paragraph("• <b>Espaço Multiuso (Praça da Escola):</b> Salão de ~7,0 m livres com bancos dobráveis laterais para 50 pessoas, mesas didáticas rebatíveis para 25 estudantes e pontos de amarração para 20 redes de dormir.", bullet_style))
story.append(Paragraph("• <b>Serviços de Apoio:</b> Sanitário fechado a boreste equipado com tanque séptico de retenção (zero descarte em manguezais e rios) e copa/cozinha a bombordo com fogão a gás e pia.", bullet_style))
story.append(Paragraph("• <b>Propulsão Mista:</b> Plano vélico tradicional de saveiro (vela de içar / carangueja + buja) como propulsão primária, complementado por motor diesel marítimo de centro (~60-85 HP) para manobra e travessia contra correnteza.", bullet_style))
story.append(Spacer(1, 10))

# Assinatura técnica
story.append(HRFlowable(width="100%", thickness=1, color=secondary_color, spaceAfter=8))
story.append(Paragraph(
    "<b>Documento elaborado pela Assistência Técnica Naval Brana / EEE para o aluno Luciano Mandú.</b><br/>"
    "<i>Escola das Águas - Preservação Cultural e Engenharia Naval Aplicada.</i>",
    subtitle_style
))

doc.build(story)
print(f"PDF gerado com sucesso em: {pdf_path}")
