#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Gerador de relatórios em HTML - Aparência profissional
"""
import os
import json
from datetime import datetime
from typing import List, Dict, Any

from .app_console import fc_log
try:
    import subprocess
    import webbrowser
    BROWSER_PDF_AVAILABLE = True
except ImportError:
    BROWSER_PDF_AVAILABLE = False


def _load_noise_history() -> List[Dict[str, Any]]:
    """Carrega histórico de testes do noise_db.json"""
    current_dir = os.path.dirname(os.path.abspath(__file__))
    db_path = os.path.join(current_dir, 'noise_db.json')
    
    if not os.path.exists(db_path):
        return []
    
    try:
        with open(db_path, 'r', encoding='utf-8') as f:
            data = json.load(f)
        return data.get('test_history', [])
    except Exception:
        return []


def _calculate_severity(max_value: float, avg_value: float) -> str:
    """Calcula severidade baseada na diferença entre ruído máximo e médio"""
    try:
        from .i18n import t
    except ImportError:
        from i18n import t
    
    diff = max_value - avg_value
    if diff <= 3:
        return t('noise.severity_low')
    elif 3 < diff <= 6:
        return t('noise.severity_medium')
    elif 6 < diff <= 9:
        return t('noise.severity_high')
    else:
        return t('noise.severity_very_high')


def _get_system_info() -> Dict[str, str]:
    """Coleta informações do sistema"""
    # Formata data conforme idioma
    try:
        from .i18n import get_translator
    except ImportError:
        from i18n import get_translator
    translator = get_translator()
    date_format = '%d/%m/%Y %H:%M:%S' if translator.get_language() == 'pt' else '%m/%d/%y %I:%M:%S %p'
    
    return {
        'software': 'FastChecker v2.0',
        'hardware': 'RFID Reader UHF',
        'firmware': 'v1.5.2',
        'license': 'FC01-EVT 800-1000',
        'generated_at': datetime.now().strftime(date_format)
    }


def generate_html_report(output_path: str, title: str = 'Relatório de Testes - Noise Check') -> str:
    """
    Gera relatório HTML profissional
    
    Args:
        output_path: Caminho do arquivo HTML
        title: Título do relatório
        
    Returns:
        Caminho do arquivo gerado
    """
    os.makedirs(os.path.dirname(output_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
    html_content = f"""
    <!DOCTYPE html>
    <html lang="pt-BR">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>{title}</title>
        <style>
            body {{
                font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
                margin: 0;
                padding: 20px;
                background-color: #f8f9fa;
                color: #333;
            }}
            
            .container {{
                max-width: 1200px;
                margin: 0 auto;
                background: white;
                padding: 30px;
                border-radius: 8px;
                box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            }}
            
            .header {{
                text-align: center;
                margin-bottom: 40px;
                padding-bottom: 20px;
                border-bottom: 3px solid #007bff;
            }}
            
            .logo {{
                max-width: 200px;
                margin-bottom: 20px;
            }}
            
            .title {{
                font-size: 28px;
                font-weight: bold;
                color: #2c3e50;
                margin-bottom: 10px;
            }}
            
            .subtitle {{
                font-size: 16px;
                color: #6c757d;
                margin-bottom: 20px;
            }}
            
            .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;
            }}
            
            .section-title {{
                font-size: 20px;
                font-weight: bold;
                color: #2c3e50;
                margin-bottom: 20px;
                padding-bottom: 10px;
                border-bottom: 2px solid #007bff;
            }}
            
            .table-container {{
                overflow-x: auto;
                margin-bottom: 20px;
            }}
            
            table {{
                width: 100%;
                border-collapse: collapse;
                background: white;
                border-radius: 8px;
                overflow: hidden;
                box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            }}
            
            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;
            }}
            
            tr:hover {{
                background-color: #e3f2fd;
            }}
            
            .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;
            }}
            
            .numeric {{
                text-align: center;
            }}
            
            .chart-container {{
                margin: 20px 0;
                padding: 20px;
                background: white;
                border-radius: 8px;
                box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            }}
            
            .chart-title {{
                font-size: 16px;
                font-weight: bold;
                margin-bottom: 15px;
                color: #2c3e50;
            }}
            
            .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;
            }}
            
            .footer {{
                text-align: center;
                margin-top: 40px;
                padding-top: 20px;
                border-top: 1px solid #dee2e6;
                color: #6c757d;
                font-size: 12px;
            }}
            
            @media print {{
                body {{ background-color: white; }}
                .container {{ box-shadow: none; }}
                .chart-container {{ break-inside: avoid; }}
            }}
        </style>
    </head>
    <body>
        <div class="container">
            <!-- Header -->
            <div class="header">
                {f'<img src="file:///{logo_path.replace(os.sep, "/")}" alt="FastChecker Logo" class="logo">' if logo_exists else ''}
                <div class="title">{title}</div>
                <div class="subtitle">Relatório automático gerado pelo FastChecker</div>
            </div>
            
            <!-- System Info -->
            <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>
            
            <!-- Summary Table -->
            <div class="section">
                <div class="section-title">Sumário dos Testes</div>
                <div class="table-container">
                    <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:]:  # Last 15 tests
        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()]
                times = list(noise_data.keys())
                absolute_times = [v.get('absolute_time', '') for v in noise_data.values()]
                if values and times and absolute_times:
                    max_idx = values.index(max(values))
                    max_time = absolute_times[max_idx]  # Usa o horário absoluto
            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 CSS class
        severity_class = f'severity-{severity.lower().replace(" ", "-").replace("á", "a")}' if severity != '-' else ''
        
        html_content += f"""
                            <tr>
                                <td>☐</td>
                                <td>{name}</td>
                                <td class="numeric">{t.get('duration', 0)}</td>
                                <td class="numeric">{avg_v:.1f}</td>
                                <td class="numeric">{min_v:.1f}</td>
                                <td class="numeric">{max_v:.1f}</td>
                                <td>{max_time}</td>
                                <td>{ts}</td>
                                <td class="{severity_class}">{severity}</td>
                            </tr>
        """
    
    html_content += """
                        </tbody>
                    </table>
                </div>
            </div>
            
            <!-- Charts -->
    """
    
    # Add charts
    for t in tests[-6:]:  # Last 6 tests
        name = t.get('test_name', f"Teste {t.get('id','')}")
        noise_data = t.get('noise_data', {})
        
        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()]
                times = [float(k) for k in noise_data.keys()]
            else:
                values = list(noise_data.values())
                times = [float(k) for k in noise_data.keys()]
            
            if values and times:
                avg_val = sum(values) / len(values)
                min_val = min(values)
                max_val = max(values)
                severity = _calculate_severity(max_val, avg_val)
                
                # Create chart with SVG for proper lines and grid
                chart_width = 800
                chart_height = 200
                
                # Calculate positions
                x_scale = chart_width / max(times) if max(times) > 0 else 1
                y_scale = chart_height / ((-40) - (-80))  # 40 dBm range
                
                # Generate SVG path for line
                path_data = []
                for i, (time, value) in enumerate(zip(times, values)):
                    x = time * x_scale
                    y = chart_height - ((value - (-80)) * y_scale)
                    if i == 0:
                        path_data.append(f'M {x} {y}')
                    else:
                        path_data.append(f'L {x} {y}')
                
                # Generate grid lines
                grid_lines = []
                # Horizontal grid lines (dBm)
                for dbm in range(-80, -35, 5):
                    y = chart_height - ((dbm - (-80)) * y_scale)
                    grid_lines.append(f'<line x1="0" y1="{y}" x2="{chart_width}" y2="{y}" stroke="#ddd" stroke-width="1" stroke-dasharray="2,2"/>')
                
                # Vertical grid lines (time)
                for time_mark in range(0, int(max(times)) + 1, 2):
                    x = time_mark * x_scale
                    grid_lines.append(f'<line x1="{x}" y1="0" x2="{x}" y2="{chart_height}" stroke="#ddd" stroke-width="1" stroke-dasharray="2,2"/>')
                
                # Generate points
                points = []
                for time, value in zip(times, values):
                    x = time * x_scale
                    y = chart_height - ((value - (-80)) * y_scale)
                    points.append(f'<circle cx="{x}" cy="{y}" r="3" fill="#8B4513" stroke="white" stroke-width="2"/>')
                
                html_content += f"""
            <div class="chart-container">
                <div class="chart-title">Noise Check - {name}</div>
                <div style="width: 100%; overflow-x: auto;">
                    <svg width="{chart_width}" height="{chart_height + 40}" style="border: 1px solid #ddd; background: #f8f9fa;">
                        <!-- Grid lines -->
                        {''.join(grid_lines)}
                        
                        <!-- Chart line -->
                        <path d="{' '.join(path_data)}" stroke="#8B4513" stroke-width="2" fill="none"/>
                        
                        <!-- Data points -->
                        {''.join(points)}
                        
                        <!-- Y-axis labels -->
                        <text x="5" y="15" font-size="10" fill="#666">-40</text>
                        <text x="5" y="{chart_height/4 + 10}" font-size="10" fill="#666">-65</text>
                        <text x="5" y="{chart_height/2 + 10}" font-size="10" fill="#666">-60</text>
                        <text x="5" y="{chart_height*3/4 + 10}" font-size="10" fill="#666">-55</text>
                        <text x="5" y="{chart_height - 5}" font-size="10" fill="#666">-80</text>
                        
                        <!-- X-axis labels -->
                        <text x="0" y="{chart_height + 20}" font-size="10" fill="#666">0s</text>
                        <text x="{chart_width/4}" y="{chart_height + 20}" font-size="10" fill="#666">{max(times)/4:.0f}s</text>
                        <text x="{chart_width/2}" y="{chart_height + 20}" font-size="10" fill="#666">{max(times)/2:.0f}s</text>
                        <text x="{chart_width*3/4}" y="{chart_height + 20}" font-size="10" fill="#666">{max(times)*3/4:.0f}s</text>
                        <text x="{chart_width - 20}" y="{chart_height + 20}" font-size="10" fill="#666">{max(times):.0f}s</text>
                        
                        <!-- Axis labels -->
                        <text x="{chart_width/2}" y="{chart_height + 35}" font-size="12" fill="#333" text-anchor="middle">Tempo (s)</text>
                    </svg>
                </div>
            </div>
                """
    
    # Add CSS for chart points
    chart_css = """
        <style>
            .chart-point {
                position: absolute;
                width: 6px;
                height: 6px;
                background-color: #8B4513;
                border-radius: 50%;
                border: 2px solid white;
                box-shadow: 0 1px 3px rgba(0,0,0,0.3);
            }
        </style>
    """
    
    html_content += f"""
        </div>
        
        <div class="footer">
            Relatório gerado automaticamente pelo FastChecker<br>
            Para mais informações, consulte a documentação do sistema
        </div>
    </div>
    {chart_css}
    </body>
    </html>
    """
    
    # Write HTML file
    with open(output_path, 'w', encoding='utf-8') as f:
        f.write(html_content)
    
    return output_path


def generate_pdf_from_html(html_path: str, pdf_path: str = None) -> str:
    """
    Converte relatório HTML para PDF usando o navegador
    
    Args:
        html_path: Caminho do arquivo HTML
        pdf_path: Caminho do PDF de saída (opcional)
        
    Returns:
        Caminho do arquivo PDF gerado
    """
    if not BROWSER_PDF_AVAILABLE:
        raise ImportError("Bibliotecas necessárias não disponíveis")
    
    if pdf_path is None:
        pdf_path = html_path.replace('.html', '.pdf')
    
    try:
        # Abre o HTML no navegador e instrui o usuário a imprimir como PDF
        webbrowser.open(f'file:///{os.path.abspath(html_path).replace(os.sep, "/")}')
        
        fc_log("html_report", f'📄 HTML aberto no navegador')
        fc_log("html_report", f'💡 Para gerar PDF:')
        fc_log("html_report", f'   1. Pressione Ctrl+P no navegador')
        fc_log("html_report", f'   2. Selecione "Salvar como PDF"')
        fc_log("html_report", f'   3. Salve como: {pdf_path}')
        
        # Retorna o caminho esperado
        return pdf_path
        
    except Exception as e:
        fc_log("html_report", f'❌ Erro ao abrir HTML: {e}')
        raise


def generate_full_report(html_path: str = None, pdf_path: str = None) -> Dict[str, str]:
    """
    Gera relatório completo (HTML + PDF)
    
    Args:
        html_path: Caminho do HTML (opcional)
        pdf_path: Caminho do PDF (opcional)
        
    Returns:
        Dicionário com caminhos dos arquivos gerados
    """
    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')
    
    # Gera HTML
    html_result = generate_html_report(html_path)
    
    results = {'html': html_result}
    
    # Tenta gerar PDF
    try:
        pdf_result = generate_pdf_from_html(html_result, pdf_path)
        results['pdf'] = pdf_result
        fc_log("html_report", f'📄 Relatório HTML gerado: {html_result}')
        fc_log("html_report", f'💡 Instruções para gerar PDF foram exibidas')
    except ImportError:
        fc_log("html_report", f'⚠️ PDF não gerado - Dependências não disponíveis')
        fc_log("html_report", f'📄 Apenas HTML gerado: {html_result}')
    except Exception as e:
        fc_log("html_report", f'❌ Erro ao gerar PDF: {e}')
        fc_log("html_report", f'📄 Apenas HTML gerado: {html_result}')
    
    return results


if __name__ == '__main__':
    # Gera relatório completo (HTML + PDF se possível)
    results = generate_full_report()
    fc_log("html_report", f'Resultado: {results}')
