#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Gerador de HTML para conversão manual em PDF (sem mensagens no rodapé)
"""
import os
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_report(html_path: str = None) -> str:
    """
    Gera um relatório HTML limpo para conversão manual em PDF
    """
    if html_path is None:
        html_path = os.path.join('docs', 'Report_Clean.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()
    
    # 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 limpo
    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: 1cm;
                size: A4;
            }}
            
            body {{ 
                font-family: 'Segoe UI', sans-serif; 
                margin: 0; 
                padding: 20px; 
                color: #333; 
                background: white;
            }}
            
            .container {{ 
                max-width: 100%; 
                margin: 0 auto; 
                background: white; 
                padding: 0;
            }}
            
            .header {{ 
                text-align: center; 
                margin-bottom: 40px; 
                border-bottom: 3px solid #007bff; 
                padding-bottom: 20px;
            }}
            
            .title {{ 
                font-size: 28px; 
                font-weight: bold; 
                color: #2c3e50; 
                margin: 0;
            }}
            
            .subtitle {{
                font-size: 14px;
                color: #666;
                margin-top: 10px;
            }}
            
            .info-grid {{ 
                display: grid; 
                grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); 
                gap: 20px; 
                margin-bottom: 30px; 
                padding: 20px; 
                background-color: #f8f9fa; 
                border-radius: 5px;
            }}
            
            .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; 
                page-break-inside: avoid;
            }}
            
            .section-title {{ 
                font-size: 20px; 
                font-weight: bold; 
                color: #2c3e50; 
                margin-bottom: 20px; 
                border-bottom: 2px solid #007bff; 
                padding-bottom: 5px;
            }}
            
            table {{ 
                width: 100%; 
                border-collapse: collapse; 
                background: white; 
                margin-bottom: 30px;
            }}
            
            th {{ 
                background-color: #007bff; 
                color: white; 
                padding: 12px 8px; 
                text-align: center; 
                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: 15px; 
                background: white; 
                page-break-inside: avoid; 
                border: 1px solid #ddd;
                border-radius: 5px;
            }}
            
            .chart-title {{ 
                font-size: 16px; 
                font-weight: bold; 
                margin-bottom: 15px; 
                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: 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; 
            }}
            
            /* Remove todas as informações do navegador */
            @media print {{
                @page {{
                    margin: 1cm;
                    size: A4;
                }}
                
                body {{
                    margin: 0;
                    padding: 0;
                    background: white;
                }}
                
                .container {{
                    box-shadow: none;
                }}
                
                /* Remove URLs e caminhos */
                a[href] {{
                    color: inherit;
                    text-decoration: none;
                }}
                
                /* Remove informações do navegador */
                body::before,
                body::after {{
                    display: none !important;
                }}
            }}
        </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: 15px;">
                    <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_report()
    
    fc_log("pdf_manual", f'✅ HTML limpo gerado: {html_path}')
    fc_log("pdf_manual", '🌐 Abrindo no navegador...')
    
    # Abre no navegador
    webbrowser.open(f'file:///{os.path.abspath(html_path)}')
    
    fc_log("pdf_manual", '💡 Para gerar PDF sem mensagens no rodapé:')
    fc_log("pdf_manual", '   1. Pressione Ctrl+P')
    fc_log("pdf_manual", '   2. Selecione "Salvar como PDF"')
    fc_log("pdf_manual", '   3. Salve como: docs/Report_Final.pdf')
    fc_log("pdf_manual", '   4. O PDF ficará limpo, sem mensagens do navegador!')
