#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Gerador de PDF usando apenas bibliotecas padrão do Python
"""
import os
import tempfile
import webbrowser
from html_report_generator import _load_noise_history, _get_system_info, _calculate_severity
from image_chart_generator import generate_all_charts

from .app_console import fc_log
def generate_clean_html_for_pdf(html_path: str = None) -> str:
    """
    Gera HTML otimizado para conversão manual em PDF
    """
    if html_path is None:
        html_path = os.path.join('docs', 'Report_Final.html')
    
    # Garante que o diretório existe
    os.makedirs(os.path.dirname(html_path), exist_ok=True)
    
    tests = _load_noise_history()
    sysinfo = _get_system_info()
    
    # HTML template otimizado para PDF
    html_content = f"""
    <!DOCTYPE html>
    <html lang="pt-BR">
    <head>
        <meta charset="UTF-8">
        <title>Relatório de Testes - Noise Check</title>
        <style>
            /* Reset para impressão */
            * {{
                box-sizing: border-box;
                margin: 0;
                padding: 0;
            }}
            
            @page {{
                margin: 1cm;
                size: A4;
                @bottom-center {{
                    content: "Página " counter(page) " de " counter(pages);
                    font-size: 10px;
                    color: #666;
                }}
            }}
            
            body {{ 
                font-family: 'Segoe UI', Arial, 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: 0;
            }}
            
            .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; 
            }}
            
            /* Otimizações para impressão */
            @media print {{
                @page {{
                    margin: 1cm;
                    size: A4;
                }}
                
                body {{
                    font-size: 11px;
                    line-height: 1.3;
                }}
                
                .container {{
                    padding: 0;
                }}
                
                .chart-container {{
                    page-break-inside: avoid;
                }}
                
                .section {{
                    page-break-inside: avoid;
                }}
                
                /* Remove URLs e links */
                a[href] {{
                    color: inherit;
                    text-decoration: none;
                }}
                
                /* Remove elementos de navegação */
                .no-print {{
                    display: none !important;
                }}
            }}
            
            /* Instruções para o usuário */
            .instructions {{
                background: #e3f2fd;
                border: 1px solid #2196f3;
                border-radius: 5px;
                padding: 15px;
                margin: 20px 0;
                font-size: 12px;
                color: #1976d2;
            }}
            
            .instructions h3 {{
                margin: 0 0 10px 0;
                color: #1976d2;
            }}
            
            .instructions ol {{
                margin: 10px 0 0 20px;
            }}
            
            .instructions li {{
                margin: 5px 0;
            }}
        </style>
    </head>
    <body>
        <div class="container">
            <div class="instructions no-print">
                <h3>📄 Instruções para Gerar PDF</h3>
                <ol>
                    <li>Pressione <strong>Ctrl+P</strong> para imprimir</li>
                    <li>Selecione <strong>"Salvar como PDF"</strong> como destino</li>
                    <li>Configure as margens como <strong>"Mínimo"</strong></li>
                    <li>Marque <strong>"Gráficos de fundo"</strong> se disponível</li>
                    <li>Clique em <strong>"Salvar"</strong></li>
                    <li>O PDF ficará limpo, sem mensagens do navegador!</li>
                </ol>
            </div>
            
            <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>
    """
    
    # Salva o arquivo HTML
    with open(html_path, 'w', encoding='utf-8') as f:
        f.write(html_content)
    
    return html_path

if __name__ == '__main__':
    html_path = generate_clean_html_for_pdf()
    
    fc_log("pdf_simple", f'✅ HTML otimizado gerado: {html_path}')
    fc_log("pdf_simple", '🌐 Abrindo no navegador...')
    
    # Abre no navegador
    webbrowser.open(f'file:///{os.path.abspath(html_path)}')
    
    fc_log("pdf_simple", '💡 Instruções para gerar PDF limpo:')
    fc_log("pdf_simple", '   1. Pressione Ctrl+P no navegador')
    fc_log("pdf_simple", '   2. Selecione "Salvar como PDF"')
    fc_log("pdf_simple", '   3. Configure margens como "Mínimo"')
    fc_log("pdf_simple", '   4. Marque "Gráficos de fundo" se disponível')
    fc_log("pdf_simple", '   5. Salve como: docs/Report_Final.pdf')
    fc_log("pdf_simple", '   6. O PDF ficará limpo, sem mensagens do navegador!')
