#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Gerador automático de PDF a partir do relatório HTML
"""
import os
import subprocess
import tempfile
from html_report_generator import generate_html_report


def generate_pdf_automatically(html_path: str = None, pdf_path: str = None) -> str:
    """
    Gera PDF automaticamente usando o navegador Chrome/Edge em modo headless
    
    Args:
        html_path: Caminho do arquivo HTML (opcional)
        pdf_path: Caminho do PDF de saída (opcional)
        
    Returns:
        Caminho do arquivo PDF gerado
    """
    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)
    
    # Converte caminho para formato absoluto
    html_abs_path = os.path.abspath(html_path)
    pdf_abs_path = os.path.abspath(pdf_path)
    
    # Lista de navegadores para tentar
    browsers = [
        # Chrome
        {
            'path': r'C:\Program Files\Google\Chrome\Application\chrome.exe',
            'args': ['--headless', '--disable-gpu', '--print-to-pdf=' + pdf_abs_path, '--print-to-pdf-no-header', '--no-first-run', '--disable-extensions', '--disable-default-apps', '--disable-web-security', '--disable-features=VizDisplayCompositor', '--hide-scrollbars', '--mute-audio', '--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage']
        },
        # Chrome (x86)
        {
            'path': r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe',
            'args': ['--headless', '--disable-gpu', '--print-to-pdf=' + pdf_abs_path, '--print-to-pdf-no-header', '--no-first-run', '--disable-extensions', '--disable-default-apps', '--disable-web-security', '--disable-features=VizDisplayCompositor', '--hide-scrollbars', '--mute-audio', '--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage']
        },
        # Edge
        {
            'path': r'C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe',
            'args': ['--headless', '--disable-gpu', '--print-to-pdf=' + pdf_abs_path, '--print-to-pdf-no-header', '--no-first-run', '--disable-extensions', '--disable-default-apps', '--disable-web-security']
        },
        # Edge (nova versão)
        {
            'path': r'C:\Program Files\Microsoft\Edge\Application\msedge.exe',
            'args': ['--headless', '--disable-gpu', '--print-to-pdf=' + pdf_abs_path, '--print-to-pdf-no-header', '--no-first-run', '--disable-extensions', '--disable-default-apps', '--disable-web-security']
        }
    ]
    
    for browser in browsers:
        if os.path.exists(browser['path']):
            try:
                print(f"🔄 Tentando gerar PDF com: {os.path.basename(browser['path'])}")
                
                # Adiciona a URL ao final dos argumentos
                args = [browser['path']] + browser['args'] + [f'file:///{html_abs_path}']
                
                # Executa o navegador
                result = subprocess.run(args, capture_output=True, text=True, timeout=30)
                
                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'❌ Falha ao gerar PDF: {result.stderr}')
                    
            except subprocess.TimeoutExpired:
                print(f'⏰ Timeout ao gerar PDF com {os.path.basename(browser["path"])}')
            except Exception as e:
                print(f'❌ Erro ao executar {os.path.basename(browser["path"])}: {e}')
    
    # Se nenhum navegador funcionou, tenta com Python + webbrowser
    print("🔄 Tentando método alternativo...")
    try:
        import webbrowser
        webbrowser.open(f'file:///{html_abs_path}')
        
        print(f'📄 HTML aberto no navegador padrão')
        print(f'💡 Para gerar PDF:')
        print(f'   1. Pressione Ctrl+P')
        print(f'   2. Selecione "Salvar como PDF"')
        print(f'   3. Salve como: {pdf_abs_path}')
        
        return pdf_abs_path
        
    except Exception as e:
        print(f'❌ Erro ao abrir HTML: {e}')
        raise Exception("Não foi possível gerar o PDF automaticamente")


def generate_pdf_only(pdf_path: str = None) -> dict:
    """
    Gera apenas o PDF (HTML temporário é criado e removido)
    
    Args:
        pdf_path: Caminho do PDF de saída (opcional)
        
    Returns:
        Dicionário com informações do PDF gerado
    """
    print("🔄 Gerando relatório PDF...")
    
    if pdf_path is None:
        pdf_path = os.path.join('docs', 'Report.pdf')
    
    # Garante que o diretório do PDF existe
    os.makedirs(os.path.dirname(pdf_path), exist_ok=True)
    
    # 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}")
        
        # Gera PDF a partir do HTML temporário
        pdf_result = generate_pdf_automatically(temp_html_path, pdf_path)
        
        return {
            'pdf': pdf_result,
            'success': True,
            'temp_html': 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
        try:
            if os.path.exists(temp_html_path):
                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}")


def _generate_html_content() -> str:
    """Gera o conteúdo HTML do relatório"""
    from html_report_generator import _load_noise_history, _get_system_info, _calculate_severity
    from image_chart_generator import generate_all_charts
    
    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)
    
    # Logo base64 se existir
    logo_base64 = ""
    if logo_exists:
        import base64
        with open(logo_path, 'rb') as logo_file:
            logo_base64 = base64.b64encode(logo_file.read()).decode()
    
    # HTML template simplificado
    html_content = f"""
    <!DOCTYPE html>
    <html lang="pt-BR">
    <head>
        <meta charset="UTF-8">
        <title>Relatório de Testes - Noise Check</title>
        <style>
            body {{ font-family: 'Segoe UI', sans-serif; margin: 20px; color: #333; }}
            .container {{ max-width: 1200px; margin: 0 auto; background: white; padding: 30px; }}
            .header {{ text-align: center; margin-bottom: 40px; border-bottom: 3px solid #007bff; }}
            .title {{ font-size: 28px; font-weight: bold; color: #2c3e50; }}
            .info-grid {{ display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px; margin-bottom: 30px; padding: 20px; background-color: #f8f9fa; }}
            .info-item {{ display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid #dee2e6; }}
            .info-label {{ font-weight: bold; color: #495057; }}
            .info-value {{ color: #212529; }}
            .section {{ margin-bottom: 40px; }}
            .section-title {{ font-size: 20px; font-weight: bold; color: #2c3e50; margin-bottom: 20px; border-bottom: 2px solid #007bff; }}
            table {{ width: 100%; border-collapse: collapse; background: white; }}
            th {{ background-color: #007bff; color: white; padding: 12px 8px; text-align: left; font-weight: bold; font-size: 12px; }}
            td {{ padding: 10px 8px; border-bottom: 1px solid #dee2e6; font-size: 11px; 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; break-inside: avoid; }}
            .chart-title {{ font-size: 16px; font-weight: bold; margin-bottom: 15px; color: #2c3e50; page-break-after: avoid; break-after: avoid; }}
            .chart-content {{ page-break-inside: avoid; break-inside: avoid; overflow: visible; width: 100%; overflow-x: visible; }}
            .stats-box {{ display: inline-block; background: #f8f9fa; padding: 10px 15px; margin: 5px; border-radius: 5px; border-left: 4px solid #007bff; }}
            .stats-label {{ font-size: 10px; color: #6c757d; font-weight: bold; }}
            .stats-value {{ font-size: 14px; font-weight: bold; color: #2c3e50; }}
            
            @media print {{
                .chart-container {{ page-break-inside: avoid !important; break-inside: avoid !important; }}
                .chart-title {{ page-break-after: avoid !important; break-after: avoid !important; }}
                .chart-content {{ page-break-inside: avoid !important; break-inside: avoid !important; }}
                body {{ background-color: white; }}
                .container {{ box-shadow: none; }}
                
                /* Tenta ocultar rodapé do navegador */
                @page {{ 
                    margin: 0.5in;
                    @bottom-left {{ content: ""; }}
                    @bottom-center {{ content: ""; }}
                    @bottom-right {{ content: ""; }}
                }}
                
                body {{ margin: 0; padding: 0; }}
                
                /* Remove URLs e caminhos de arquivo */
                a[href^="file://"] {{ display: none !important; }}
                a[href^="tmp"] {{ display: none !important; }}
                
                /* Tenta ocultar elementos do navegador */
                body::after {{ display: none !important; }}
                html::after {{ display: none !important; }}
            }}
            
            /* CSS adicional para tentar ocultar rodapé */
            body {{
                position: relative;
            }}
            
            body::after {{
                content: "";
                position: fixed;
                bottom: 0;
                left: 0;
                right: 0;
                height: 30px;
                background: white;
                z-index: 9999;
                display: block;
            }}
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                {"<img src='data:image/png;base64," + logo_base64 + "' style='height: 60px; margin-bottom: 10px;' />" if logo_base64 else ""}
                <div class="title">Relatório de Testes - Noise Check</div>
                <div>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" style="width: 100%; text-align: center; overflow: hidden;">
                    <img src="data:image/png;base64,{image_base64}" style="width: 100%; height: auto; max-width: 100%; border: 1px solid #ddd; object-fit: contain;" />
                </div>
            </div>
        """
    
    html_content += """
        </div>
    </body>
    </html>
    """
    
    return html_content


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'⚠️ Erro ao gerar PDF: {result.get("error", "Erro desconhecido")}')
        print(f'💡 Siga as instruções para gerar o PDF manualmente')
