#!/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
from .i18n import t
import tempfile

from .app_console import fc_log
from .shell_open import open_path_with_default_app
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)
    
    fc_log("reportlab_pdf", "🔄 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(t('pdf.report_title_noise'), title_style))
    story.append(Spacer(1, 20))
    
    # Informações do sistema
    sysinfo = _get_system_info()
    story.append(Paragraph(t('pdf.system_info'), heading_style))
    
    # Tabela de informações
    info_data = [
        [t('pdf.software'), sysinfo['software']],
        [t('pdf.hardware'), sysinfo['hardware']],
        [t('pdf.firmware'), sysinfo['firmware']],
        [t('pdf.license'), sysinfo['license']],
        [t('pdf.generated_at'), 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(t('pdf.test_summary_noise'), heading_style))
    
    # Cabeçalho da tabela
    table_data = [[t('noise.plot'), t('noise.test_name'), t('noise.duration'),
                   t('noise.avg_noise'), t('noise.min_noise'), t('noise.max_noise'),
                   t('noise.max_noise_time'), t('noise.date_time'), t('noise.severity')]]
    
    # 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(t('pdf.noise_chart_section').format(name=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)
    
    fc_log("reportlab_pdf", f'✅ PDF gerado com ReportLab: {pdf_path}')
    return pdf_path

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