import json
from reportlab.lib.pagesizes import letter
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib import colors
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, HRFlowable
from reportlab.pdfgen import canvas

with open("/home/magdalena/eee/alunos/caliandra/similares_dados.json", "r") as f:
    d = json.load(f)

pdf_path = "/home/magdalena/eee/alunos/caliandra/Estudo_de_Similar_Caliandra.pdf"
proj_nome = d.get("projetista", "Caliandra")
proj_data = d.get("data", "15/09/2026")
emb_pret = d.get("embarcacao_pretendida", "")
rec_txt = d.get("recomendacao", "")
caso_res = d.get("caso_de_uso_resumo", "")
crit_sel = d.get("criterios_selecao", "")
leit_par = d.get("leitura_parametrica", "")

class NumberedCanvas(canvas.Canvas):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._saved_page_states = []

    def showPage(self):
        self._saved_page_states.append(dict(self.__dict__))
        self._startPage()

    def save(self):
        num_pages = len(self._saved_page_states)
        for state in self._saved_page_states:
            self.__dict__.update(state)
            self.draw_page_number(num_pages)
            canvas.Canvas.showPage(self)
        canvas.Canvas.save(self)

    def draw_page_number(self, page_count):
        self.saveState()
        self.setFont("Helvetica", 8)
        self.setFillColor(colors.HexColor("#5A626B"))
        # Header
        self.drawString(54, 750, "BRANA · Escola de Arquitetura e Engenharia Naval | Estaleiro Escola Embrião")
        self.drawRightString(612 - 54, 750, "Estudo de Similares — Projeto O RESGATE")
        self.setStrokeColor(colors.HexColor("#D3D9DC"))
        self.setLineWidth(0.5)
        self.line(54, 742, 612 - 54, 742)
        
        # Footer
        self.line(54, 45, 612 - 54, 45)
        self.drawString(54, 32, f"Projetista: {proj_nome} · Data: {proj_data}")
        self.drawRightString(612 - 54, 32, f"Página {self._pageNumber} de {page_count}")
        self.restoreState()

doc = SimpleDocTemplate(
    pdf_path,
    pagesize=letter,
    leftMargin=54,
    rightMargin=54,
    topMargin=60,
    bottomMargin=60
)

styles = getSampleStyleSheet()

title_style = ParagraphStyle(
    "DocTitle",
    parent=styles["Normal"],
    fontName="Helvetica-Bold",
    fontSize=18,
    leading=22,
    textColor=colors.HexColor("#1F2429"),
    spaceAfter=4
)

subtitle_style = ParagraphStyle(
    "DocSubtitle",
    parent=styles["Normal"],
    fontName="Helvetica",
    fontSize=9.5,
    leading=13,
    textColor=colors.HexColor("#5A626B"),
    spaceAfter=10
)

sec_title_style = ParagraphStyle(
    "SecTitle",
    parent=styles["Normal"],
    fontName="Helvetica-Bold",
    fontSize=10.5,
    leading=14,
    textColor=colors.HexColor("#C4262E"),
    spaceBefore=7,
    spaceAfter=3
)

p_style = ParagraphStyle(
    "Para",
    parent=styles["Normal"],
    fontName="Helvetica",
    fontSize=8,
    leading=11.5,
    textColor=colors.HexColor("#333333"),
    spaceAfter=5
)

th_style = ParagraphStyle(
    "TH",
    parent=styles["Normal"],
    fontName="Helvetica-Bold",
    fontSize=7,
    leading=9.5,
    textColor=colors.white,
    alignment=1
)

td_style = ParagraphStyle(
    "TD",
    parent=styles["Normal"],
    fontName="Helvetica",
    fontSize=7,
    leading=9.5,
    textColor=colors.HexColor("#1F2429"),
    alignment=1
)

td_left = ParagraphStyle(
    "TDLeft",
    parent=styles["Normal"],
    fontName="Helvetica-Bold",
    fontSize=7,
    leading=9.5,
    textColor=colors.HexColor("#1F2429")
)

story = []

story.append(Paragraph("Estudo de Similares (Parametric Study)", title_style))
story.append(Paragraph(f"Embarcação Pretendida: <b>{emb_pret}</b> | Projetista: <b>{proj_nome}</b>", subtitle_style))

# Seção 1: Resumo do Caso de Uso e Critérios
story.append(Paragraph("1. Resumo do Caso de Uso e Critérios de Seleção", sec_title_style))
story.append(HRFlowable(width="100%", thickness=0.5, color=colors.HexColor("#C4262E"), spaceAfter=5, spaceBefore=0))
story.append(Paragraph(f"<b>Caso de Uso:</b> {caso_res}", p_style))
story.append(Paragraph(f"<b>Critérios de Seleção:</b> {crit_sel}", p_style))
story.append(Spacer(1, 3))

# Seção 2: Tabela Comparativa Paramétrica
story.append(Paragraph("2. Tabela Comparativa de Embarcações Similares", sec_title_style))
story.append(HRFlowable(width="100%", thickness=0.5, color=colors.HexColor("#C4262E"), spaceAfter=5, spaceBefore=0))

table_data = [
    [
        Paragraph("Parâmetro", th_style),
        Paragraph("O RESGATE<br/>(Projeto)", th_style),
        Paragraph("SAFE 2910<br/>(SAFE Boats)", th_style),
        Paragraph("29 Defiant<br/>(Metal Shark)", th_style),
        Paragraph("31 Full Cabin<br/>(Life Proof)", th_style),
        Paragraph("TX-860 OB<br/>(Vanguard)", th_style),
        Paragraph("9.8M SAR<br/>(ASIS Boats)", th_style)
    ],
    [
        Paragraph("LOA (m)", td_left),
        Paragraph("<b>9,00</b>", td_style),
        Paragraph("9,55", td_style),
        Paragraph("8,84", td_style),
        Paragraph("9,45", td_style),
        Paragraph("8,60", td_style),
        Paragraph("10,30", td_style)
    ],
    [
        Paragraph("Boca BOA (m)", td_left),
        Paragraph("<b>3,00</b>", td_style),
        Paragraph("3,05", td_style),
        Paragraph("2,59", td_style),
        Paragraph("3,05", td_style),
        Paragraph("3,06", td_style),
        Paragraph("3,17", td_style)
    ],
    [
        Paragraph("Calado (m)", td_left),
        Paragraph("<b>0,63</b>", td_style),
        Paragraph("0,51", td_style),
        Paragraph("0,53", td_style),
        Paragraph("0,61", td_style),
        Paragraph("0,55", td_style),
        Paragraph("0,60", td_style)
    ],
    [
        Paragraph("Peso / Desloc. (kg)", td_left),
        Paragraph("<b>5.582 (12 pax)</b>", td_style),
        Paragraph("4.626", td_style),
        Paragraph("3.855", td_style),
        Paragraph("4.309", td_style),
        Paragraph("2.800", td_style),
        Paragraph("3.210", td_style)
    ],
    [
        Paragraph("Deadrise Popa (°)", td_left),
        Paragraph("<b>15,3° (24° proa)</b>", td_style),
        Paragraph("25,0°", td_style),
        Paragraph("22,0°", td_style),
        Paragraph("24,0°", td_style),
        Paragraph("24,0°", td_style),
        Paragraph("23,0°", td_style)
    ],
    [
        Paragraph("Potência (HP)", td_left),
        Paragraph("<b>600 (2x 300)</b>", td_style),
        Paragraph("600 - 1000", td_style),
        Paragraph("500 - 600", td_style),
        Paragraph("600 - 900", td_style),
        Paragraph("500", td_style),
        Paragraph("600 - 800", td_style)
    ],
    [
        Paragraph("Vel. Máx. (nós)", td_left),
        Paragraph("<b>38 - 40</b>", td_style),
        Paragraph("55", td_style),
        Paragraph("50", td_style),
        Paragraph("52", td_style),
        Paragraph("48", td_style),
        Paragraph("46", td_style)
    ],
    [
        Paragraph("Vel. Cruzeiro (nós)", td_left),
        Paragraph("<b>28 - 30</b>", td_style),
        Paragraph("32", td_style),
        Paragraph("30", td_style),
        Paragraph("32", td_style),
        Paragraph("30", td_style),
        Paragraph("28", td_style)
    ],
    [
        Paragraph("Combustível (L)", td_left),
        Paragraph("<b>500</b>", td_style),
        Paragraph("946 (250 gal)", td_style),
        Paragraph("757 (200 gal)", td_style),
        Paragraph("757 (200 gal)", td_style),
        Paragraph("500", td_style),
        Paragraph("435", td_style)
    ],
    [
        Paragraph("Lotação (pessoas)", td_left),
        Paragraph("<b>12 (4 trip + 8 resg)</b>", td_style),
        Paragraph("8 - 10", td_style),
        Paragraph("6 - 8", td_style),
        Paragraph("8 - 10", td_style),
        Paragraph("15", td_style),
        Paragraph("15", td_style)
    ]
]

comp_table = Table(table_data, colWidths=[84, 70, 70, 70, 70, 70, 70])
comp_table.setStyle(TableStyle([
    ("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#1F2429")),
    ("BACKGROUND", (1, 1), (1, -1), colors.HexColor("#EFF2F3")),
    ("GRID", (0, 0), (-1, -1), 0.5, colors.HexColor("#D3D9DC")),
    ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
    ("TOPPADDING", (0, 0), (-1, -1), 2.5),
    ("BOTTOMPADDING", (0, 0), (-1, -1), 2.5),
]))

story.append(comp_table)
story.append(Spacer(1, 6))

# Seção 3: Leitura Paramétrica e Recomendações
story.append(Paragraph("3. Leitura Paramétrica e Análise de Viabilidade", sec_title_style))
story.append(HRFlowable(width="100%", thickness=0.5, color=colors.HexColor("#C4262E"), spaceAfter=5, spaceBefore=0))
story.append(Paragraph(leit_par, p_style))
story.append(Paragraph(f"<b>Recomendações Técnicas:</b> {rec_txt}", p_style))
story.append(Spacer(1, 3))

# Seção 4: Fontes Consultadas
story.append(Paragraph("4. Relação de Embarcações e Fontes Oficiais Auditadas", sec_title_style))
story.append(HRFlowable(width="100%", thickness=0.5, color=colors.HexColor("#C4262E"), spaceAfter=5, spaceBefore=0))

for s in d.get("similares", []):
    f_info = s["fontes"][0]
    est_nome = s.get("estaleiro", "")
    s_nome = s.get("nome", "")
    s_ano = s.get("ano", "N/A")
    s_porq = s.get("porque_similar", "")
    f_nome = f_info.get("nome", "")
    f_url = f_info.get("url", "")
    f_data = f_info.get("data_acesso", "")
    p_sim = (
        f"• <b>{est_nome} — {s_nome}</b> ({s_ano})<br/>"
        f"<i>Justificativa:</i> {s_porq}<br/>"
        f"<i>Fonte:</i> {f_nome} — <font color=\"#2E6B72\"><u>{f_url}</u></font> (Acesso: {f_data})"
    )
    story.append(Paragraph(p_sim, p_style))

doc.build(story, canvasmaker=NumberedCanvas)
print("PDF do Estudo de Similar atualizado!")
