import os
from reportlab.lib.pagesizes import letter, landscape
from reportlab.lib import colors
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, HRFlowable
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch

pdf_path = "/home/magdalena/eee/alunos/alberico-de-carvalho-santiago/Projeto_Integral_Area_Velica_Saveiro_6_30m.pdf"

doc = SimpleDocTemplate(
    pdf_path,
    pagesize=landscape(letter),
    rightMargin=28,
    leftMargin=28,
    topMargin=26,
    bottomMargin=26
)

styles = getSampleStyleSheet()

primary_color = colors.HexColor("#0F2B48")
secondary_color = colors.HexColor("#B45309")
dark_neutral = colors.HexColor("#1E293B")
light_neutral = colors.HexColor("#F8FAFC")
border_color = colors.HexColor("#CBD5E1")

title_style = ParagraphStyle(
    'DocTitle',
    parent=styles['Heading1'],
    fontName='Helvetica-Bold',
    fontSize=13,
    leading=17,
    textColor=primary_color,
    alignment=1,
    spaceAfter=2
)

subtitle_style = ParagraphStyle(
    'DocSubtitle',
    parent=styles['Normal'],
    fontName='Helvetica',
    fontSize=8.5,
    leading=11,
    textColor=secondary_color,
    alignment=1,
    spaceAfter=5
)

section_heading = ParagraphStyle(
    'SectionHeading',
    parent=styles['Heading2'],
    fontName='Helvetica-Bold',
    fontSize=9.5,
    leading=12,
    textColor=primary_color,
    spaceBefore=4,
    spaceAfter=2
)

body_style = ParagraphStyle(
    'BodyDark',
    parent=styles['Normal'],
    fontName='Helvetica',
    fontSize=7.5,
    leading=10,
    textColor=dark_neutral,
    spaceAfter=2
)

bullet_style = ParagraphStyle(
    'BulletDark',
    parent=body_style,
    leftIndent=8,
    firstLineIndent=-6,
    spaceAfter=1.5
)

table_header_style = ParagraphStyle(
    'TableHeader',
    parent=styles['Normal'],
    fontName='Helvetica-Bold',
    fontSize=6.8,
    leading=8.5,
    textColor=colors.white,
    alignment=1
)

table_body_style = ParagraphStyle(
    'TableBody',
    parent=styles['Normal'],
    fontName='Helvetica',
    fontSize=6.5,
    leading=8.2,
    textColor=dark_neutral,
    alignment=1
)

table_body_bold = ParagraphStyle(
    'TableBodyBold',
    parent=styles['Normal'],
    fontName='Helvetica-Bold',
    fontSize=6.5,
    leading=8.2,
    textColor=primary_color,
    alignment=1
)

table_body_left = ParagraphStyle(
    'TableBodyLeft',
    parent=table_body_style,
    alignment=0
)

story = []

# Cabeçalho
story.append(Paragraph("PROJETO INTEGRAL DO PLANO VÉLICO — MINI SAVEIRO DE VELA DE IÇAR (6,30 m)", title_style))
story.append(Paragraph("<b>Cálculo de Área Vélica, Centro Vélico (CE), Equilíbrio de Leme (Lead) e Plano de Rizos</b> | Aluno: Alberico | Brana / EEE", subtitle_style))
story.append(HRFlowable(width="100%", thickness=1.2, color=secondary_color, spaceAfter=4))

# 1. Geometria das Velas e Cotas Oficiais
story.append(Paragraph("1. Dimensões Geométricas Oficiais das Velas e Mastreação", section_heading))

t_geom = [
    [
        Paragraph("Elemento Vélico", table_header_style),
        Paragraph("Símbolo", table_header_style),
        Paragraph("Dimensão Real (m)", table_header_style),
        Paragraph("Escala 1:25 (cm)", table_header_style),
        Paragraph("Área Ativa (m²)", table_header_style),
        Paragraph("Centro Vélico Local (X, Y)", table_header_style),
        Paragraph("Função Náutica e Cabos", table_header_style)
    ],
    [
        Paragraph("Vela de Içar (Grande)", table_body_bold),
        Paragraph("P, E, Ve", table_body_style),
        Paragraph("P=4,20 m | E=4,50 m<br/>Ve=3,40 m | Valuma=4,80 m", table_body_style),
        Paragraph("P=16,8 cm | E=18,0 cm<br/>Ve=13,6 cm | Valuma=19,2 cm", table_body_style),
        Paragraph("<b>16,50 m²</b><br/>(73,3% total)", table_body_bold),
        Paragraph("X1 = 2,35 m<br/>Y1 = 3,25 m", table_body_style),
        Paragraph("Vela quadrangular áurica. Envergada na carangueja (Ve) e no mastro (P). Força motriz principal.", table_body_left)
    ],
    [
        Paragraph("Bujarrona (Buja)", table_body_bold),
        Paragraph("I, J", table_body_style),
        Paragraph("I=4,80 m | J=3,80 m<br/>Testa=5,10 m | Esteira=2,70 m", table_body_style),
        Paragraph("I=19,2 cm | J=15,2 cm<br/>Testa=20,4 cm | Esteira=10,8 cm", table_body_style),
        Paragraph("<b>6,00 m²</b><br/>(26,7% total)", table_body_bold),
        Paragraph("X2 = 5,28 m<br/>Y2 = 2,28 m", table_body_style),
        Paragraph("Vela triangular amurada no baucot (gurupés). Puxa a proa a sotavento, aliviando o leme.", table_body_left)
    ],
    [
        Paragraph("TOTAL PLANO VÉLICO", table_body_bold),
        Paragraph("At", table_body_style),
        Paragraph("<b>Casco: 6,30 m</b><br/>(7,80 m c/ baucot)", table_body_style),
        Paragraph("<b>Modelo: 25,2 cm</b><br/>(31,2 cm c/ baucot)", table_body_style),
        Paragraph("<b>22,50 m²</b><br/>(100% pano)", table_body_bold),
        Paragraph("<b>X_ce = 3,13 m<br/>Y_ce = 2,99 m</b>", table_body_bold),
        Paragraph("<b>Relação SA/D = 18,2</b> (Excelente potência para ventos brandos e médios de baía).", table_body_left)
    ]
]

t_table_geom = Table(t_geom, colWidths=[1.5*inch, 0.7*inch, 2.0*inch, 1.8*inch, 1.1*inch, 1.3*inch, 2.6*inch])
t_table_geom.setStyle(TableStyle([
    ('BACKGROUND', (0,0), (-1,0), primary_color),
    ('ALIGN', (0,0), (-1,-1), 'CENTER'),
    ('VALIGN', (0,0), (-1,-1), 'MIDDLE'),
    ('GRID', (0,0), (-1,-1), 0.5, border_color),
    ('ROWBACKGROUNDS', (0,1), (-1,-1), [light_neutral, colors.white]),
    ('TOPPADDING', (0,0), (-1,-1), 2),
    ('BOTTOMPADDING', (0,0), (-1,-1), 2),
]))
story.append(t_table_geom)
story.append(Spacer(1, 4))

# 2. Equilíbrio de Leme (Lead)
story.append(Paragraph("2. Equilíbrio Aerodinâmico e Hidrodinâmico (Cálculo do Lead)", section_heading))
story.append(Paragraph(
    "Para que um barco a vela navegue em linha reta sem cansar o braço do timoneiro, o <b>Centro Vélico (CE)</b> deve ficar ligeiramente à vante do <b>Centro de Resistência Lateral do Casco (CLR)</b>. Essa folga é chamada de <b>LEAD</b>:<br/>"
    "• <b>Posição do CLR (Casco com LWL = 5,60 m):</b> O centro de deriva do fundo chato com lastro interno fica a 46% do LWL a partir da popa: <b>X_clr = 2,75 m</b>.<br/>"
    "• <b>Posição do Centro Vélico Combinado (CE):</b> Calculado pela média ponderada das áreas: <i>X_ce = (16,5 × 2,35 + 6,0 × 5,28) / 22,5 = <b>3,13 m</b></i>.<br/>"
    "• <b>Distância do Lead:</b> <i>Lead = X_ce - X_clr = 3,13 m - 2,75 m = <b>0,38 metro</b></i>.<br/>"
    "• <b>Lead em Porcentagem da Linha d'Água:</b> <i>(0,38 / 5,60) × 100 = <b>6,8% do LWL</b></i>. "
    "A literatura clássica de arquitetura naval (Gerr, Skene) recomenda entre <b>5% e 9%</b> para sloops tradicionais. "
    "O seu barco atingiu o ponto de equilíbrio perfeito: tem uma leve tendência ardente de segurança (se largar o leme, o barco aponta para o vento e para), sem ficar pesado na mão!",
    body_style
))
story.append(Spacer(1, 3))

# 3. Plano de Rizos
story.append(Paragraph("3. Plano Operacional de Rizos (Navegação Conforme a Força do Vento)", section_heading))

t_reef_data = [
    [
        Paragraph("Escala Beaufort / Vento", table_header_style),
        Paragraph("Velocidade do Vento", table_header_style),
        Paragraph("Configuração do Velame", table_header_style),
        Paragraph("Área Ativa (m²)", table_header_style),
        Paragraph("Velocidade do Casco", table_header_style),
        Paragraph("Comportamento Náutico / Recomendações", table_header_style)
    ],
    [
        Paragraph("Força 1 a 2 (Brisa Leve)", table_body_bold),
        Paragraph("1 a 6 nós", table_body_style),
        Paragraph("Pano Total: Vela de Içar + Buja Aberta", table_body_style),
        Paragraph("22,5 m² (100%)", table_body_style),
        Paragraph("2,5 a 4,0 nós", table_body_style),
        Paragraph("Navegação suave em águas calmas; ideal para relaxar e ensinar novos velejadores.", table_body_left)
    ],
    [
        Paragraph("Força 3 (Brisa Fraca/Moderada)", table_body_bold),
        Paragraph("7 a 10 nós", table_body_style),
        Paragraph("Pano Total: Vela de Içar + Buja Aberta", table_body_style),
        Paragraph("22,5 m² (100%)", table_body_style),
        Paragraph("5,0 a 5,5 nós", table_body_style),
        Paragraph("Condição perfeita de passeio de domingo na Baía de Todos-os-Santos. Barco aprumado com adernamento de apenas ~6°.", table_body_left)
    ],
    [
        Paragraph("Força 4 (Brisa Moderada/Fresca)", table_body_bold),
        Paragraph("11 a 16 nós", table_body_style),
        Paragraph("<b>1º Rizo</b> na Vela de Içar + Buja Aberta", table_body_style),
        Paragraph("17,5 m² (78%)", table_body_style),
        Paragraph("5,8 a 6,2 nós", table_body_style),
        Paragraph("Velocidade máxima teórica de casco atingida! O casco apoia no bojo chato e desliza estável cortando a marola.", table_body_left)
    ],
    [
        Paragraph("Força 5 (Brisa Forte)", table_body_bold),
        Paragraph("17 a 21 nós", table_body_style),
        Paragraph("<b>2º Rizo</b> na Vela de Içar + Buja Rizante", table_body_style),
        Paragraph("12,5 m² (55%)", table_body_style),
        Paragraph("5,5 nós", table_body_style),
        Paragraph("Rebaixa o centro de gravidade vélico; navegação segura e firme sem forçar o mastro nem a tripulação.", table_body_left)
    ],
    [
        Paragraph("Força 6+ (Vento Muito Forte)", table_body_bold),
        Paragraph("22+ nós (Temporal)", table_body_style),
        Paragraph("Arria a Vela Grande / Sob Buja ou Motor", table_body_style),
        Paragraph("5,0 m² (ou Diesel)", table_body_style),
        Paragraph("4,5 a 5,0 nós", table_body_style),
        Paragraph("Liga o motor diesel Yanmar/Agrale de 12 CV e volta para a marina com total controle e segurança.", table_body_left)
    ]
]

t_table_reef = Table(t_reef_data, colWidths=[1.6*inch, 1.2*inch, 2.2*inch, 1.2*inch, 1.2*inch, 3.6*inch])
t_table_reef.setStyle(TableStyle([
    ('BACKGROUND', (0,0), (-1,0), primary_color),
    ('ALIGN', (0,0), (-1,-1), 'CENTER'),
    ('VALIGN', (0,0), (-1,-1), 'MIDDLE'),
    ('GRID', (0,0), (-1,-1), 0.5, border_color),
    ('ROWBACKGROUNDS', (0,1), (-1,-1), [light_neutral, colors.white]),
    ('TOPPADDING', (0,0), (-1,-1), 2),
    ('BOTTOMPADDING', (0,0), (-1,-1), 2),
]))
story.append(t_table_reef)

doc.build(story)
print("PDF Integral Area Velica gerado com sucesso!")
