#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Gerador de PDF usando ReportLab (biblioteca Python nativa)
"""
import os
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, Image
from reportlab.lib import colors
from reportlab.lib.enums import TA_CENTER, TA_LEFT
from html_report_generator import _load_noise_history, _get_system_info, _calculate_severity
from image_chart_generator import generate_all_charts
import tempfile

def generate_pdf_with_reportlab(pdf_path: str = None) -> str:
    """
    Gera PDF usando ReportLab (biblioteca Python nativa)
    """
    if pdf_path is None:
        pdf_path = os.path.join('docs', 'Report_ReportLab.pdf')
    
    # Garante que o diretório existe
    os.makedirs(os.path.dirname(pdf_path), exist_ok=True)
    
    print("🔄 Gerando PDF com ReportLab...")
    
    # Cria o documento PDF
    doc = SimpleDocTemplate(pdf_path, pagesize=A4, 
                          rightMargin=72, leftMargin=72, 
                          topMargin=72, bottomMargin=18)
    
    # Estilos
    styles = getSampleStyleSheet()
    title_style = ParagraphStyle(
        'CustomTitle',
        parent=styles['Heading1'],
        fontSize=24,
        spaceAfter=30,
        alignment=TA_CENTER,
        textColor=colors.HexColor('#2c3e50')
    )
    
    heading_style = ParagraphStyle(
        'CustomHeading',
        parent=styles['Heading2'],
        fontSize=16,
        spaceAfter=12,
        textColor=colors.HexColor('#2c3e50')
    )
    
    # Conteúdo do documento
    story = []
    
    # Título
    story.append(Paragraph("Relatório de Testes - Noise Check", title_style))
    story.append(Spacer(1, 20))
    
    # Informações do sistema
    sysinfo = _get_system_info()
    story.append(Paragraph("Informações do Sistema", heading_style))
    
    # Tabela de informações
    info_data = [
        ['Software:', sysinfo['software']],
        ['Hardware:', sysinfo['hardware']],
        ['Firmware:', sysinfo['firmware']],
        ['Licença:', sysinfo['license']],
        ['Gerado em:', sysinfo['generated_at']]
    ]
    
    info_table = Table(info_data, colWidths=[2*inch, 4*inch])
    info_table.setStyle(TableStyle([
        ('BACKGROUND', (0, 0), (0, -1), colors.HexColor('#f8f9fa')),
        ('TEXTCOLOR', (0, 0), (-1, -1), colors.black),
        ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ('FONTNAME', (0, 0), (0, -1), 'Helvetica-Bold'),
        ('FONTSIZE', (0, 0), (-1, -1), 10),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 12),
        ('BACKGROUND', (1, 0), (1, -1), colors.white),
    ]))
    
    story.append(info_table)
    story.append(Spacer(1, 30))
    
    # Tabela de resumo dos testes
    tests = _load_noise_history()
    story.append(Paragraph("Sumário dos Testes", heading_style))
    
    # Cabeçalho da tabela
    table_data = [['Plot', 'Nome do Teste', 'Duração (s)', 'Ruído Médio (dBm)', 
                   'Ruído Mínimo (dBm)', 'Ruído Máximo (dBm)', 'Hora Ruído Máximo', 
                   'Data/Hora', 'Severidade']]
    
    # Dados dos testes
    for t in tests[-15:]:
        name = t.get('test_name', '-')
        ts = t.get('timestamp', '-')
        noise_data = t.get('noise_data', {})
        
        values = []
        max_time = ''
        if isinstance(noise_data, dict) and noise_data:
            first_val = next(iter(noise_data.values()))
            if isinstance(first_val, dict) and 'value' in first_val:
                values = [v['value'] for v in noise_data.values()]
                absolute_times = [v.get('absolute_time', '') for v in noise_data.values()]
                if values and absolute_times:
                    max_idx = values.index(max(values))
                    max_time = absolute_times[max_idx]
            else:
                values = list(noise_data.values())
        
        if values:
            avg_v = sum(values) / len(values)
            min_v = min(values)
            max_v = max(values)
            severity = _calculate_severity(max_v, avg_v)
        else:
            avg_v = min_v = max_v = 0
            severity = '-'
        
        table_data.append(['☐', name, str(t.get('duration', 0)), 
                          f"{avg_v:.1f}", f"{min_v:.1f}", f"{max_v:.1f}", 
                          max_time, ts, severity])
    
    # Cria a tabela
    test_table = Table(table_data, colWidths=[0.5*inch, 1.5*inch, 0.8*inch, 1*inch, 
                                              1*inch, 1*inch, 1.2*inch, 1.5*inch, 1*inch])
    test_table.setStyle(TableStyle([
        ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#007bff')),
        ('TEXTCOLOR', (0, 0), (-1, 0), colors.white),
        ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
        ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
        ('FONTNAME', (0, 1), (-1, -1), 'Helvetica'),
        ('FONTSIZE', (0, 0), (-1, -1), 8),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 8),
        ('TOPPADDING', (0, 0), (-1, -1), 8),
        ('GRID', (0, 0), (-1, -1), 1, colors.black),
        ('ROWBACKGROUNDS', (0, 1), (-1, -1), [colors.white, colors.HexColor('#f8f9fa')])
    ]))
    
    story.append(test_table)
    story.append(Spacer(1, 30))
    
    # Gráficos
    charts = generate_all_charts(tests)
    for name, image_base64 in charts:
        story.append(Paragraph(f"Noise Check - {name}", heading_style))
        
        # Salva a imagem temporariamente
        with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as tmp_file:
            import base64
            tmp_file.write(base64.b64decode(image_base64))
            tmp_path = tmp_file.name
        
        try:
            # Adiciona a imagem ao PDF
            img = Image(tmp_path, width=7*inch, height=2.5*inch)
            story.append(img)
            story.append(Spacer(1, 20))
        finally:
            # Remove o arquivo temporário
            os.unlink(tmp_path)
    
    # Gera o PDF
    doc.build(story)
    
    print(f'✅ PDF gerado com ReportLab: {pdf_path}')
    return pdf_path

if __name__ == '__main__':
    try:
        pdf_path = generate_pdf_with_reportlab()
        print(f'🎯 Relatório PDF gerado!')
        print(f'   PDF:  {pdf_path}')
        
        # Abre o PDF
        if os.path.exists(pdf_path):
            os.startfile(pdf_path)
            print('📄 PDF aberto automaticamente!')
    except ImportError:
        print('❌ ReportLab não está instalado!')
        print('💡 Execute: pip install reportlab')
    except Exception as e:
        print(f'❌ Erro ao gerar PDF: {e}')
