#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Gerador de PDF usando wkhtmltopdf (mais controle sobre o output)
"""
import os
import subprocess
import tempfile
from html_report_generator import _load_noise_history, _get_system_info, _calculate_severity
from image_chart_generator import generate_all_charts

def generate_pdf_with_wkhtmltopdf(html_path: str = None, pdf_path: str = None) -> str:
    """
    Gera PDF usando wkhtmltopdf (controle total sobre o output)
    """
    if html_path is None:
        html_path = os.path.join('docs', 'Report.html')
    if pdf_path is None:
        pdf_path = html_path.replace('.html', '.pdf')
    
    # Garante que o diretório existe
    os.makedirs(os.path.dirname(pdf_path), exist_ok=True)
    
    # Caminhos absolutos
    html_abs_path = os.path.abspath(html_path)
    pdf_abs_path = os.path.abspath(pdf_path)
    
    # Configurações do wkhtmltopdf para PDF limpo
    wkhtmltopdf_options = [
        '--page-size', 'A4',
        '--margin-top', '0.75in',
        '--margin-right', '0.75in',
        '--margin-bottom', '0.75in',
        '--margin-left', '0.75in',
        '--encoding', 'UTF-8',
        '--disable-smart-shrinking',
        '--print-media-type',
        '--no-outline',
        '--disable-external-links',
        '--disable-internal-links',
        '--disable-forms',
        '--disable-javascript',
        '--quiet',
        '--dpi', '300',
        '--image-quality', '94'
    ]
    
    # Comando completo
    cmd = ['wkhtmltopdf'] + wkhtmltopdf_options + [html_abs_path, pdf_abs_path]
    
    try:
        print(f"🔄 Gerando PDF com wkhtmltopdf...")
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
        
        if result.returncode == 0 and os.path.exists(pdf_abs_path):
            print(f'✅ PDF gerado com sucesso: {pdf_abs_path}')
            return pdf_abs_path
        else:
            print(f'❌ Erro ao gerar PDF: {result.stderr}')
            return None
            
    except subprocess.TimeoutExpired:
        print('⏰ Timeout ao gerar PDF')
        return None
    except FileNotFoundError:
        print('❌ wkhtmltopdf não encontrado. Tentando método alternativo...')
        return None
    except Exception as e:
        print(f'❌ Erro ao executar wkhtmltopdf: {e}')
        return None

def generate_html_content() -> str:
    """Gera o conteúdo HTML do relatório"""
    tests = _load_noise_history()
    sysinfo = _get_system_info()
    
    # Logo path
    root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
    logo_path = os.path.join(root, 'assets', 'images', 'fasttag_logo.png')
    logo_exists = os.path.exists(logo_path)
    
    # HTML template otimizado para wkhtmltopdf
    html_content = f"""
    <!DOCTYPE html>
    <html lang="pt-BR">
    <head>
        <meta charset="UTF-8">
        <title>Relatório de Testes - Noise Check</title>
        <style>
            @page {{
                margin: 0.75in;
                size: A4;
            }}
            
            body {{ 
                font-family: 'Segoe UI', sans-serif; 
                margin: 0; 
                padding: 0; 
                color: #333; 
                background: white;
                font-size: 12px;
                line-height: 1.4;
            }}
            
            .container {{ 
                max-width: 100%; 
                margin: 0 auto; 
                background: white; 
                padding: 20px;
            }}
            
            .header {{ 
                text-align: center; 
                margin-bottom: 30px; 
                border-bottom: 3px solid #007bff; 
                padding-bottom: 15px;
            }}
            
            .title {{ 
                font-size: 24px; 
                font-weight: bold; 
                color: #2c3e50; 
                margin: 0;
            }}
            
            .subtitle {{
                font-size: 12px;
                color: #666;
                margin-top: 5px;
            }}
            
            .info-grid {{ 
                display: grid; 
                grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); 
                gap: 15px; 
                margin-bottom: 25px; 
                padding: 15px; 
                background-color: #f8f9fa; 
                border-radius: 5px;
            }}
            
            .info-item {{ 
                display: flex; 
                justify-content: space-between; 
                padding: 5px 0; 
                border-bottom: 1px solid #dee2e6; 
                font-size: 11px;
            }}
            
            .info-label {{ 
                font-weight: bold; 
                color: #495057; 
            }}
            
            .info-value {{ 
                color: #212529; 
            }}
            
            .section {{ 
                margin-bottom: 30px; 
                page-break-inside: avoid;
            }}
            
            .section-title {{ 
                font-size: 18px; 
                font-weight: bold; 
                color: #2c3e50; 
                margin-bottom: 15px; 
                border-bottom: 2px solid #007bff; 
                padding-bottom: 5px;
            }}
            
            table {{ 
                width: 100%; 
                border-collapse: collapse; 
                background: white; 
                margin-bottom: 25px;
                font-size: 10px;
            }}
            
            th {{ 
                background-color: #007bff; 
                color: white; 
                padding: 8px 6px; 
                text-align: center; 
                font-weight: bold; 
                font-size: 10px; 
            }}
            
            td {{ 
                padding: 6px; 
                border-bottom: 1px solid #dee2e6; 
                font-size: 9px; 
                text-align: center; 
            }}
            
            tr:nth-child(even) {{ 
                background-color: #f8f9fa; 
            }}
            
            .severity-baixa {{ 
                color: #28a745; 
                font-weight: bold; 
            }}
            
            .severity-media {{ 
                color: #ffc107; 
                font-weight: bold; 
            }}
            
            .severity-alta {{ 
                color: #dc3545; 
                font-weight: bold; 
            }}
            
            .severity-muito-alta {{ 
                color: #721c24; 
                font-weight: bold; 
            }}
            
            .chart-container {{ 
                margin: 20px 0; 
                padding: 10px; 
                background: white; 
                page-break-inside: avoid; 
                border: 1px solid #ddd;
                border-radius: 5px;
            }}
            
            .chart-title {{ 
                font-size: 14px; 
                font-weight: bold; 
                margin-bottom: 10px; 
                color: #2c3e50; 
            }}
            
            .chart-content {{ 
                text-align: center; 
                overflow: hidden; 
            }}
            
            .chart-content img {{
                width: 100%;
                max-width: 100%;
                height: auto;
                border: 1px solid #ddd;
            }}
            
            .stats-box {{ 
                display: inline-block; 
                background: #f8f9fa; 
                padding: 8px 12px; 
                margin: 3px; 
                border-radius: 5px; 
                border-left: 4px solid #007bff; 
                font-size: 10px;
            }}
            
            .stats-label {{ 
                font-size: 8px; 
                color: #6c757d; 
                font-weight: bold; 
            }}
            
            .stats-value {{ 
                font-size: 12px; 
                font-weight: bold; 
                color: #2c3e50; 
            }}
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <div class="title">Relatório de Testes - Noise Check</div>
                <div class="subtitle">Relatório automático gerado pelo FastChecker</div>
            </div>
            
            <div class="section">
                <div class="section-title">Informações do Sistema</div>
                <div class="info-grid">
                    <div class="info-item"><span class="info-label">Software:</span><span class="info-value">{sysinfo['software']}</span></div>
                    <div class="info-item"><span class="info-label">Hardware:</span><span class="info-value">{sysinfo['hardware']}</span></div>
                    <div class="info-item"><span class="info-label">Firmware:</span><span class="info-value">{sysinfo['firmware']}</span></div>
                    <div class="info-item"><span class="info-label">Licença:</span><span class="info-value">{sysinfo['license']}</span></div>
                    <div class="info-item"><span class="info-label">Gerado em:</span><span class="info-value">{sysinfo['generated_at']}</span></div>
                </div>
            </div>
            
            <div class="section">
                <div class="section-title">Sumário dos Testes</div>
                <table>
                    <thead>
                        <tr>
                            <th>Plot</th><th>Nome do Teste</th><th>Duração (s)</th><th>Ruído Médio (dBm)</th>
                            <th>Ruído Mínimo (dBm)</th><th>Ruído Máximo (dBm)</th><th>Hora Ruído Máximo</th>
                            <th>Data/Hora</th><th>Severidade</th>
                        </tr>
                    </thead>
                    <tbody>
    """
    
    # Add table rows
    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 = '-'
        
        severity_class = f'severity-{severity.lower().replace(" ", "-").replace("á", "a")}' if severity != '-' else ''
        
        html_content += f"""
                        <tr>
                            <td>☐</td><td>{name}</td><td>{t.get('duration', 0)}</td><td>{avg_v:.1f}</td>
                            <td>{min_v:.1f}</td><td>{max_v:.1f}</td><td>{max_time}</td><td>{ts}</td>
                            <td class="{severity_class}">{severity}</td>
                        </tr>
        """
    
    html_content += """
                    </tbody>
                </table>
            </div>
            
            <!-- Charts -->
    """
    
    # Gera gráficos como imagens
    charts = generate_all_charts(tests)
    
    for name, image_base64 in charts:
        # Busca dados do teste para estatísticas
        test_data = None
        for t in tests:
            if t.get('test_name') == name:
                test_data = t
                break
        
        if test_data:
            noise_data = test_data.get('noise_data', {})
            
            if isinstance(noise_data, dict) and noise_data:
                # Calcula estatísticas
                sorted_items = sorted(noise_data.items(), key=lambda x: float(x[0]))
                first_val = next(iter(noise_data.values()))
                
                if isinstance(first_val, dict) and 'value' in first_val:
                    values = [data['value'] for _, data in sorted_items]
                else:
                    values = [value for _, value in sorted_items]
                
                if values:
                    avg_val = sum(values) / len(values)
                    min_val = min(values)
                    max_val = max(values)
                    severity = _calculate_severity(max_val, avg_val)
                else:
                    avg_val = min_val = max_val = 0
                    severity = '-'
            else:
                avg_val = min_val = max_val = 0
                severity = '-'
        else:
            avg_val = min_val = max_val = 0
            severity = '-'
        
        html_content += f"""
            <div class="chart-container">
                <div class="chart-title">Noise Check - {name}</div>
                <div class="chart-content">
                    <img src="data:image/png;base64,{image_base64}" />
                </div>
                <div style="margin-top: 10px;">
                    <div class="stats-box">
                        <div class="stats-label">Médio</div>
                        <div class="stats-value">{avg_val:.1f} dBm</div>
                    </div>
                    <div class="stats-box">
                        <div class="stats-label">Mínimo</div>
                        <div class="stats-value">{min_val:.1f} dBm</div>
                    </div>
                    <div class="stats-box">
                        <div class="stats-label">Máximo</div>
                        <div class="stats-value">{max_val:.1f} dBm</div>
                    </div>
                    <div class="stats-box">
                        <div class="stats-label">Severidade</div>
                        <div class="stats-value">{severity}</div>
                    </div>
                </div>
            </div>
        """
    
    html_content += """
        </div>
    </body>
    </html>
    """
    
    return html_content

def generate_pdf_only(pdf_path: str = None) -> dict:
    """
    Gera apenas o PDF (HTML temporário é criado e removido)
    """
    print("🔄 Gerando relatório PDF...")
    
    if pdf_path is None:
        pdf_path = os.path.join('docs', 'Report_Clean.pdf')
    
    # Cria arquivo HTML temporário
    with tempfile.NamedTemporaryFile(mode='w', suffix='.html', delete=False, encoding='utf-8') as temp_html:
        temp_html_path = temp_html.name
        
        # Gera o conteúdo HTML
        html_content = generate_html_content()
        temp_html.write(html_content)
    
    try:
        print(f"📝 HTML temporário criado: {temp_html_path}")
        
        # Tenta gerar PDF com wkhtmltopdf
        pdf_result = generate_pdf_with_wkhtmltopdf(temp_html_path, pdf_path)
        
        if pdf_result:
            return {
                'pdf': pdf_result,
                'success': True,
                'temp_html': temp_html_path
            }
        else:
            # Fallback para método manual
            print("🔄 wkhtmltopdf não disponível, usando método manual...")
            return {
                'pdf': None,
                'success': False,
                'error': 'wkhtmltopdf não disponível',
                'temp_html': temp_html_path,
                'html_path': temp_html_path
            }
        
    except Exception as e:
        print(f'❌ Erro ao gerar PDF: {e}')
        return {
            'pdf': None,
            'success': False,
            'error': str(e),
            'temp_html': temp_html_path
        }
    
    finally:
        # Remove o arquivo HTML temporário se PDF foi gerado com sucesso
        try:
            if os.path.exists(temp_html_path) and pdf_result:
                os.unlink(temp_html_path)
                print(f"🗑️ HTML temporário removido: {temp_html_path}")
        except Exception as e:
            print(f"⚠️ Não foi possível remover HTML temporário: {e}")

if __name__ == '__main__':
    result = generate_pdf_only()
    
    if result['success']:
        print(f'🎯 Relatório PDF gerado!')
        print(f'   PDF:  {result["pdf"]}')
        
        # Abre o PDF se foi gerado
        if result['pdf'] and os.path.exists(result['pdf']):
            os.startfile(result['pdf'])
            print('📄 PDF aberto automaticamente!')
    else:
        print(f'⚠️ Método automático não disponível: {result.get("error", "Erro desconhecido")}')
        if 'html_path' in result:
            print(f'💡 HTML gerado: {result["html_path"]}')
            print(f'💡 Para gerar PDF manualmente:')
            print(f'   1. Abra o arquivo HTML no navegador')
            print(f'   2. Pressione Ctrl+P')
            print(f'   3. Selecione "Salvar como PDF"')
            print(f'   4. O PDF ficará limpo, sem mensagens do navegador!')
