#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Gerador de relatórios em HTML para Antenna Check - Aparência profissional
Baseado no formato do Noise Check
"""
import os
import json
from datetime import datetime
from typing import List, Dict, Any
from decimal import Decimal

try:
    from .i18n import get_translator, t
except ImportError:
    from i18n import get_translator, t

try:
    import subprocess
    import webbrowser
    BROWSER_PDF_AVAILABLE = True
except ImportError:
    BROWSER_PDF_AVAILABLE = False


from .app_console import fc_log
def _load_antenna_history() -> List[Dict[str, Any]]:
    """Carrega histórico de testes do antenna_db.json"""
    current_dir = os.path.dirname(os.path.abspath(__file__))
    db_path = os.path.join(current_dir, 'antenna_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_vswr_from_return_loss(return_loss_db: float) -> float:
    """Calcula VSWR a partir do Return Loss"""
    if return_loss_db <= 0:
        return 3.5  # VSWR alto para valores inválidos
    
    # Return Loss = -20 * log10(|Γ|)
    # |Γ| = 10^(-Return Loss / 20)
    reflection_coeff = 10 ** (-return_loss_db / 20)
    
    # VSWR = (1 + |Γ|) / (1 - |Γ|)
    if abs(reflection_coeff - 1.0) < 1e-10:
        return 3.5  # VSWR alto quando |Γ| ≈ 1
    else:
        vswr = (1 + reflection_coeff) / (1 - reflection_coeff)
        return min(vswr, 3.5)  # Limita VSWR máximo


def _apply_fit_to_data_logic(freqs: List[float], values: List[float], chart_width: int, chart_height: int) -> tuple:
    """
    Aplica a mesma lógica do botão 'Fit to Data' para ajuste automático dos gráficos
    
    Args:
        freqs: Lista de frequências
        values: Lista de valores
        chart_width: Largura do gráfico
        chart_height: Altura do gráfico
        
    Returns:
        Tupla (x_scale, y_scale, new_x_min, new_x_max, new_y_min, new_y_max)
    """
    if not freqs or not values:
        return 1, 1, 0, 1, 0, 1
    
    # Aplica a mesma lógica do _fit_to_data do antenna_module.py
    x_min, x_max = min(freqs), max(freqs)
    y_min, y_max = min(values), max(values)
    
    # Margem maior para melhor visualização - replicando exatamente a lógica do programa
    x_range = x_max - x_min
    y_range = y_max - y_min
    
    # Ajuste de margem: se range for pequeno, ainda assim dar uma folga visual
    if x_range < 10:  # Menos de 10 MHz de range (faixas estreitas)
        x_margin = max(0.5, x_range * 0.1)  # pelo menos 0.5 MHz
    else:
        x_margin = x_range * 0.05  # 5% para ranges maiores
        
    if y_range < 5:  # Menos de 5 dBm de range
        y_margin = 0.5  # 0.5 dBm de margem
    else:
        y_margin = y_range * 0.05  # 5% de margem
    
    # Define novos limites com margem
    new_x_min = max(0, x_min - x_margin)
    new_x_max = x_max + x_margin
    new_y_min = y_min - y_margin
    new_y_max = y_max + y_margin
    
    # Calcula escalas baseadas nos limites ajustados
    x_scale = chart_width / (new_x_max - new_x_min) if (new_x_max - new_x_min) > 0 else 1
    y_scale = chart_height / (new_y_max - new_y_min) if (new_y_max - new_y_min) > 0 else 1
    
    return x_scale, y_scale, new_x_min, new_x_max, new_y_min, new_y_max


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


def generate_antenna_html_report(output_path: str, title: str = 'Relatório de Testes - Antenna Check') -> str:
    """
    Gera relatório HTML profissional para Antenna Check
    
    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_antenna_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: 8px 4px;
                text-align: left;
                font-weight: bold;
                font-size: 10px;
                white-space: nowrap;
            }}
            
            td {{
                padding: 6px 4px;
                border-bottom: 1px solid #dee2e6;
                font-size: 9px;
                text-align: center;
                white-space: nowrap;
            }}
            
            tr:nth-child(even) {{
                background-color: #f8f9fa;
            }}
            
            tr:hover {{
                background-color: #e3f2fd;
            }}
            
            
            .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; 
                    font-size: 8px;
                }}
                .container {{ 
                    box-shadow: none; 
                    padding: 10px;
                    max-width: none;
                }}
                .chart-container {{ break-inside: avoid; }}
                
                /* Otimizações específicas para tabelas em PDF */
                table {{
                    font-size: 7px;
                    page-break-inside: auto;
                }}
                
                th {{
                    font-size: 8px !important;
                    padding: 4px 2px !important;
                }}
                
                td {{
                    font-size: 7px !important;
                    padding: 3px 2px !important;
                }}
                
                .table-container {{
                    overflow: visible;
                }}
                
                /* Reduz margens para aproveitar melhor o espaço */
                .section {{
                    margin-bottom: 15px;
                }}
                
                .section-title {{
                    font-size: 14px;
                    margin-bottom: 8px;
                }}
            }}
        </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>Nome do Teste</th>
                                <th>Pot (dBm)</th>
                                <th>Range (MHz)</th>
                                <th>Min RL (dBm)</th>
                                <th>VSWR</th>
                                <th>Melhor Freq (MHz)</th>
                                <th>Data/Hora</th>
                            </tr>
                        </thead>
                        <tbody>
    """
    
    # Add table rows
    for t in tests[-15:]:  # Last 15 tests
        name = t.get('description', '-')
        ts = t.get('timestamp', '-')
        power = t.get('power', 0)
        data_points = t.get('data_points', {})
        
        # Processa dados de frequência e valores
        freqs = []
        values = []
        if isinstance(data_points, dict) and data_points:
            for freq_str, value in data_points.items():
                try:
                    freq = float(freq_str)
                    if value is not None:  # Ignora pontos excluídos
                        freqs.append(freq)
                        values.append(float(value))
                except (ValueError, TypeError):
                    continue
        
        if values and freqs:
            freq_range = f"{min(freqs):.1f} a {max(freqs):.1f}" if freqs else "N/A"
            min_return_loss = min(values)
            best_freq = freqs[values.index(min_return_loss)]
            vswr = _calculate_vswr_from_return_loss(min_return_loss)
        else:
            freq_range = "N/A"
            min_return_loss = 0
            best_freq = "N/A"
            vswr = 0
        
        
        html_content += f"""
                            <tr>
                                <td>{name}</td>
                                <td class="numeric">{power}</td>
                                <td class="numeric">{freq_range}</td>
                                <td class="numeric">{min_return_loss:.2f}</td>
                                <td class="numeric">{vswr:.2f}</td>
                                <td class="numeric">{best_freq:.1f}</td>
                                <td>{ts}</td>
                            </tr>
        """
    
    html_content += """
                        </tbody>
                    </table>
                </div>
            </div>
            
            <!-- Charts -->
    """
    
    # Add charts
    for t in tests[-6:]:  # Last 6 tests
        name = t.get('description', f"Teste {t.get('id','')}")
        data_points = t.get('data_points', {})
        power = t.get('power', 0)
        
        if isinstance(data_points, dict) and data_points:
            freqs = []
            values = []
            for freq_str, value in data_points.items():
                try:
                    freq = float(freq_str)
                    if value is not None:  # Ignora pontos excluídos
                        freqs.append(freq)
                        values.append(float(value))
                except (ValueError, TypeError):
                    continue
            
            if values and freqs:
                # Ordena por frequência
                sorted_data = sorted(zip(freqs, values))
                freqs = [x[0] for x in sorted_data]
                values = [x[1] for x in sorted_data]
                
                avg_val = sum(values) / len(values)
                min_val = min(values)
                max_val = max(values)
                
                # Create chart with SVG for proper lines and grid
                chart_width = 800
                chart_height = 200
                
                # Aplica a mesma lógica do botão "Fit to Data"
                x_scale, y_scale, new_x_min, new_x_max, new_y_min, new_y_max = _apply_fit_to_data_logic(freqs, values, chart_width, chart_height)
                
                # Generate SVG path for line with separate segments (like the program)
                path_data = []
                
                # Cria segmentos separados para cada faixa de frequência (como no programa)
                if len(freqs) >= 2:
                    # Identifica gaps entre frequências para criar segmentos separados
                    segments = []
                    current_segment = [(freqs[0], values[0])]
                    
                    for i in range(1, len(freqs)):
                        # Se a diferença entre frequências é maior que 5 MHz, cria novo segmento
                        if freqs[i] - freqs[i-1] > 5:
                            segments.append(current_segment)
                            current_segment = [(freqs[i], values[i])]
                        else:
                            current_segment.append((freqs[i], values[i]))
                    segments.append(current_segment)
                    
                    # Gera path SVG para cada segmento separadamente
                    for segment in segments:
                        if len(segment) >= 2:  # Só cria linha se tiver pelo menos 2 pontos
                            for i, (freq, value) in enumerate(segment):
                                x = (freq - new_x_min) * x_scale
                                y = chart_height - ((value - new_y_min) * y_scale)
                                if i == 0:
                                    path_data.append(f'M {x} {y}')
                                else:
                                    path_data.append(f'L {x} {y}')
                else:
                    # Fallback para linha única se tiver poucos pontos
                    for i, (freq, value) in enumerate(zip(freqs, values)):
                        x = (freq - new_x_min) * x_scale
                        y = chart_height - ((value - new_y_min) * 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) - baseado nos limites ajustados
                y_step = (new_y_max - new_y_min) / 10
                for i in range(11):
                    y_val = new_y_min + i * y_step
                    y = chart_height - ((y_val - new_y_min) * 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 (frequency) - baseado nos limites ajustados
                x_step = (new_x_max - new_x_min) / 10
                for i in range(11):
                    x_val = new_x_min + i * x_step
                    x = (x_val - new_x_min) * 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 shaded regions for frequency ranges (like the program)
                shaded_regions = []
                if len(freqs) >= 2:
                    # Cria regiões sombreadas para cada faixa de frequência dos dados
                    freq_ranges = []
                    current_range = [freqs[0]]
                    
                    for i in range(1, len(freqs)):
                        # Se a diferença entre frequências é maior que 5 MHz, cria nova região
                        if freqs[i] - freqs[i-1] > 5:
                            freq_ranges.append(current_range)
                            current_range = [freqs[i]]
                        else:
                            current_range.append(freqs[i])
                    freq_ranges.append(current_range)
                    
                    # Gera retângulos sombreados para cada faixa
                    for freq_range in freq_ranges:
                        if len(freq_range) >= 2:
                            x_start = (min(freq_range) - new_x_min) * x_scale
                            x_end = (max(freq_range) - new_x_min) * x_scale
                            width = x_end - x_start
                            shaded_regions.append(f'<rect x="{x_start}" y="0" width="{width}" height="{chart_height}" fill="#007bff" opacity="0.1"/>')
                
                # Generate points
                points = []
                for freq, value in zip(freqs, values):
                    x = (freq - new_x_min) * x_scale
                    y = chart_height - ((value - new_y_min) * y_scale)
                    points.append(f'<circle cx="{x}" cy="{y}" r="3" fill="#007bff" stroke="white" stroke-width="2"/>')
                
                html_content += f"""
            <div class="chart-container">
                <div class="chart-title">Antenna 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)}
                        
                        <!-- Shaded regions -->
                        {''.join(shaded_regions)}
                        
                        <!-- Chart line -->
                        <path d="{' '.join(path_data)}" stroke="#007bff" stroke-width="2" fill="none"/>
                        
                        <!-- Data points -->
                        {''.join(points)}
                        
                        <!-- Y-axis labels -->
                        <text x="5" y="15" font-size="10" fill="#666">{new_y_max:.1f}</text>
                        <text x="5" y="{chart_height/4 + 10}" font-size="10" fill="#666">{new_y_min + 3*(new_y_max-new_y_min)/4:.1f}</text>
                        <text x="5" y="{chart_height/2 + 10}" font-size="10" fill="#666">{new_y_min + (new_y_max-new_y_min)/2:.1f}</text>
                        <text x="5" y="{chart_height*3/4 + 10}" font-size="10" fill="#666">{new_y_min + (new_y_max-new_y_min)/4:.1f}</text>
                        <text x="5" y="{chart_height - 5}" font-size="10" fill="#666">{new_y_min:.1f}</text>
                        
                        <!-- X-axis labels -->
                        <text x="0" y="{chart_height + 20}" font-size="10" fill="#666" text-anchor="start">{new_x_min:.1f}</text>
                        <text x="{chart_width/4}" y="{chart_height + 20}" font-size="10" fill="#666" text-anchor="middle">{new_x_min + (new_x_max-new_x_min)/4:.1f}</text>
                        <text x="{chart_width/2}" y="{chart_height + 20}" font-size="10" fill="#666" text-anchor="middle">{new_x_min + (new_x_max-new_x_min)/2:.1f}</text>
                        <text x="{chart_width*3/4}" y="{chart_height + 20}" font-size="10" fill="#666" text-anchor="middle">{new_x_min + 3*(new_x_max-new_x_min)/4:.1f}</text>
                        <text x="{chart_width}" y="{chart_height + 20}" font-size="10" fill="#666" text-anchor="end">{new_x_max:.1f}</text>
                        
                        <!-- Axis labels -->
                        <text x="{chart_width/2}" y="{chart_height + 35}" font-size="12" fill="#333" text-anchor="middle">Frequência (MHz)</text>
                    </svg>
                </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>
            </div>
                """
    
    # Add CSS for chart points
    chart_css = """
        <style>
            .chart-point {
                position: absolute;
                width: 6px;
                height: 6px;
                background-color: #007bff;
                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_antenna_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("antenna_html_report", f'📄 HTML aberto no navegador')
        fc_log("antenna_html_report", f'💡 Para gerar PDF:')
        fc_log("antenna_html_report", f'   1. Pressione Ctrl+P no navegador')
        fc_log("antenna_html_report", f'   2. Selecione "Salvar como PDF"')
        fc_log("antenna_html_report", f'   3. Salve como: {pdf_path}')
        
        # Retorna o caminho esperado
        return pdf_path
        
    except Exception as e:
        fc_log("antenna_html_report", f'❌ Erro ao abrir HTML: {e}')
        raise


def generate_antenna_html_report_for_selected(output_path: str, selected_ids: List[int], title: str = 'Relatório dos Selecionados - Antenna Check') -> str:
    """
    Gera relatório HTML profissional para testes selecionados do Antenna Check
    
    Args:
        output_path: Caminho do arquivo HTML
        selected_ids: Lista de IDs dos testes selecionados
        title: Título do relatório
        
    Returns:
        Caminho do arquivo gerado
    """
    # Cria diretório se necessário
    output_dir = os.path.dirname(output_path)
    if output_dir:
        os.makedirs(output_dir, exist_ok=True)
    
    # Carrega todos os testes e filtra apenas os selecionados
    all_tests = _load_antenna_history()
    selected_tests = [test for test in all_tests if test.get('id') in selected_ids]
    
    if not selected_tests:
        raise ValueError("Nenhum teste selecionado encontrado")
    
    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: 8px 4px;
                text-align: left;
                font-weight: bold;
                font-size: 10px;
                white-space: nowrap;
            }}
            
            td {{
                padding: 6px 4px;
                border-bottom: 1px solid #dee2e6;
                font-size: 9px;
                text-align: center;
                white-space: nowrap;
            }}
            
            tr:nth-child(even) {{
                background-color: #f8f9fa;
            }}
            
            tr:hover {{
                background-color: #e3f2fd;
            }}
            
            
            .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; 
                    font-size: 8px;
                }}
                .container {{ 
                    box-shadow: none; 
                    padding: 10px;
                    max-width: none;
                }}
                .chart-container {{ break-inside: avoid; }}
                
                /* Otimizações específicas para tabelas em PDF */
                table {{
                    font-size: 7px;
                    page-break-inside: auto;
                }}
                
                th {{
                    font-size: 8px !important;
                    padding: 4px 2px !important;
                }}
                
                td {{
                    font-size: 7px !important;
                    padding: 3px 2px !important;
                }}
                
                .table-container {{
                    overflow: visible;
                }}
                
                /* Reduz margens para aproveitar melhor o espaço */
                .section {{
                    margin-bottom: 15px;
                }}
                
                .section-title {{
                    font-size: 14px;
                    margin-bottom: 8px;
                }}
            }}
        </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 class="info-item">
                        <span class="info-label">Testes Selecionados:</span>
                        <span class="info-value">{len(selected_tests)}</span>
                    </div>
                </div>
            </div>
            
            <!-- Summary Table -->
            <div class="section">
                <div class="section-title">Sumário dos Testes Selecionados</div>
                <div class="table-container">
                    <table>
                        <thead>
                            <tr>
                                <th>Nome do Teste</th>
                                <th>Pot (dBm)</th>
                                <th>Range (MHz)</th>
                                <th>Min RL (dBm)</th>
                                <th>VSWR</th>
                                <th>Melhor Freq (MHz)</th>
                                <th>Data/Hora</th>
                            </tr>
                        </thead>
                        <tbody>
    """
    
    # Add table rows for selected tests
    for t in selected_tests:
        name = t.get('description', '-')
        ts = t.get('timestamp', '-')
        power = t.get('power', 0)
        data_points = t.get('data_points', {})
        
        # Processa dados de frequência e valores
        freqs = []
        values = []
        if isinstance(data_points, dict) and data_points:
            for freq_str, value in data_points.items():
                try:
                    freq = float(freq_str)
                    if value is not None:  # Ignora pontos excluídos
                        freqs.append(freq)
                        values.append(float(value))
                except (ValueError, TypeError):
                    continue
        
        if values and freqs:
            freq_range = f"{min(freqs):.1f} a {max(freqs):.1f}" if freqs else "N/A"
            min_return_loss = min(values)
            best_freq = freqs[values.index(min_return_loss)]
            vswr = _calculate_vswr_from_return_loss(min_return_loss)
        else:
            freq_range = "N/A"
            min_return_loss = 0
            best_freq = "N/A"
            vswr = 0
        
        
        html_content += f"""
                            <tr>
                                <td>☑</td>
                                <td>{name}</td>
                                <td class="numeric">{power}</td>
                                <td class="numeric">{freq_range}</td>
                                <td class="numeric">{min_return_loss:.2f}</td>
                                <td class="numeric">{vswr:.2f}</td>
                                <td class="numeric">{best_freq:.1f}</td>
                                <td>{ts}</td>
                            </tr>
        """
    
    html_content += """
                        </tbody>
                    </table>
                </div>
            </div>
            
            <!-- Charts -->
    """
    
    # Add charts for selected tests
    for t in selected_tests:
        name = t.get('description', f"Teste {t.get('id','')}")
        data_points = t.get('data_points', {})
        power = t.get('power', 0)
        
        if isinstance(data_points, dict) and data_points:
            freqs = []
            values = []
            for freq_str, value in data_points.items():
                try:
                    freq = float(freq_str)
                    if value is not None:  # Ignora pontos excluídos
                        freqs.append(freq)
                        values.append(float(value))
                except (ValueError, TypeError):
                    continue
            
            if values and freqs:
                # Ordena por frequência
                sorted_data = sorted(zip(freqs, values))
                freqs = [x[0] for x in sorted_data]
                values = [x[1] for x in sorted_data]
                
                avg_val = sum(values) / len(values)
                min_val = min(values)
                max_val = max(values)
                
                # Create chart with SVG for proper lines and grid
                chart_width = 800
                chart_height = 200
                
                # Aplica a mesma lógica do botão "Fit to Data"
                x_scale, y_scale, new_x_min, new_x_max, new_y_min, new_y_max = _apply_fit_to_data_logic(freqs, values, chart_width, chart_height)
                
                # Generate SVG path for line with separate segments (like the program)
                path_data = []
                
                # Cria segmentos separados para cada faixa de frequência (como no programa)
                if len(freqs) >= 2:
                    # Identifica gaps entre frequências para criar segmentos separados
                    segments = []
                    current_segment = [(freqs[0], values[0])]
                    
                    for i in range(1, len(freqs)):
                        # Se a diferença entre frequências é maior que 5 MHz, cria novo segmento
                        if freqs[i] - freqs[i-1] > 5:
                            segments.append(current_segment)
                            current_segment = [(freqs[i], values[i])]
                        else:
                            current_segment.append((freqs[i], values[i]))
                    segments.append(current_segment)
                    
                    # Gera path SVG para cada segmento separadamente
                    for segment in segments:
                        if len(segment) >= 2:  # Só cria linha se tiver pelo menos 2 pontos
                            for i, (freq, value) in enumerate(segment):
                                x = (freq - new_x_min) * x_scale
                                y = chart_height - ((value - new_y_min) * y_scale)
                                if i == 0:
                                    path_data.append(f'M {x} {y}')
                                else:
                                    path_data.append(f'L {x} {y}')
                else:
                    # Fallback para linha única se tiver poucos pontos
                    for i, (freq, value) in enumerate(zip(freqs, values)):
                        x = (freq - new_x_min) * x_scale
                        y = chart_height - ((value - new_y_min) * 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) - baseado nos limites ajustados
                y_step = (new_y_max - new_y_min) / 10
                for i in range(11):
                    y_val = new_y_min + i * y_step
                    y = chart_height - ((y_val - new_y_min) * 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 (frequency) - baseado nos limites ajustados
                x_step = (new_x_max - new_x_min) / 10
                for i in range(11):
                    x_val = new_x_min + i * x_step
                    x = (x_val - new_x_min) * 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 shaded regions for frequency ranges (like the program)
                shaded_regions = []
                if len(freqs) >= 2:
                    # Cria regiões sombreadas para cada faixa de frequência dos dados
                    freq_ranges = []
                    current_range = [freqs[0]]
                    
                    for i in range(1, len(freqs)):
                        # Se a diferença entre frequências é maior que 5 MHz, cria nova região
                        if freqs[i] - freqs[i-1] > 5:
                            freq_ranges.append(current_range)
                            current_range = [freqs[i]]
                        else:
                            current_range.append(freqs[i])
                    freq_ranges.append(current_range)
                    
                    # Gera retângulos sombreados para cada faixa
                    for freq_range in freq_ranges:
                        if len(freq_range) >= 2:
                            x_start = (min(freq_range) - new_x_min) * x_scale
                            x_end = (max(freq_range) - new_x_min) * x_scale
                            width = x_end - x_start
                            shaded_regions.append(f'<rect x="{x_start}" y="0" width="{width}" height="{chart_height}" fill="#007bff" opacity="0.1"/>')
                
                # Generate points
                points = []
                for freq, value in zip(freqs, values):
                    x = (freq - new_x_min) * x_scale
                    y = chart_height - ((value - new_y_min) * y_scale)
                    points.append(f'<circle cx="{x}" cy="{y}" r="3" fill="#007bff" stroke="white" stroke-width="2"/>')
                
                html_content += f"""
            <div class="chart-container">
                <div class="chart-title">Antenna 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)}
                        
                        <!-- Shaded regions -->
                        {''.join(shaded_regions)}
                        
                        <!-- Chart line -->
                        <path d="{' '.join(path_data)}" stroke="#007bff" stroke-width="2" fill="none"/>
                        
                        <!-- Data points -->
                        {''.join(points)}
                        
                        <!-- Y-axis labels -->
                        <text x="5" y="15" font-size="10" fill="#666">{new_y_max:.1f}</text>
                        <text x="5" y="{chart_height/4 + 10}" font-size="10" fill="#666">{new_y_min + 3*(new_y_max-new_y_min)/4:.1f}</text>
                        <text x="5" y="{chart_height/2 + 10}" font-size="10" fill="#666">{new_y_min + (new_y_max-new_y_min)/2:.1f}</text>
                        <text x="5" y="{chart_height*3/4 + 10}" font-size="10" fill="#666">{new_y_min + (new_y_max-new_y_min)/4:.1f}</text>
                        <text x="5" y="{chart_height - 5}" font-size="10" fill="#666">{new_y_min:.1f}</text>
                        
                        <!-- X-axis labels -->
                        <text x="0" y="{chart_height + 20}" font-size="10" fill="#666" text-anchor="start">{new_x_min:.1f}</text>
                        <text x="{chart_width/4}" y="{chart_height + 20}" font-size="10" fill="#666" text-anchor="middle">{new_x_min + (new_x_max-new_x_min)/4:.1f}</text>
                        <text x="{chart_width/2}" y="{chart_height + 20}" font-size="10" fill="#666" text-anchor="middle">{new_x_min + (new_x_max-new_x_min)/2:.1f}</text>
                        <text x="{chart_width*3/4}" y="{chart_height + 20}" font-size="10" fill="#666" text-anchor="middle">{new_x_min + 3*(new_x_max-new_x_min)/4:.1f}</text>
                        <text x="{chart_width}" y="{chart_height + 20}" font-size="10" fill="#666" text-anchor="end">{new_x_max:.1f}</text>
                        
                        <!-- Axis labels -->
                        <text x="{chart_width/2}" y="{chart_height + 35}" font-size="12" fill="#333" text-anchor="middle">Frequência (MHz)</text>
                    </svg>
                </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>
            </div>
                """
    
    # Add CSS for chart points
    chart_css = """
        <style>
            .chart-point {
                position: absolute;
                width: 6px;
                height: 6px;
                background-color: #007bff;
                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_antenna_full_report(html_path: str = None, pdf_path: str = None) -> Dict[str, str]:
    """
    Gera relatório completo para Antenna Check (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', 'Antenna_Report.html')
    if pdf_path is None:
        pdf_path = html_path.replace('.html', '.pdf')
    
    # Gera HTML
    html_result = generate_antenna_html_report(html_path)
    
    results = {'html': html_result}
    
    # Tenta gerar PDF
    try:
        pdf_result = generate_antenna_pdf_from_html(html_result, pdf_path)
        results['pdf'] = pdf_result
        fc_log("antenna_html_report", f'📄 Relatório HTML gerado: {html_result}')
        fc_log("antenna_html_report", f'💡 Instruções para gerar PDF foram exibidas')
    except ImportError:
        fc_log("antenna_html_report", f'⚠️ PDF não gerado - Dependências não disponíveis')
        fc_log("antenna_html_report", f'📄 Apenas HTML gerado: {html_result}')
    except Exception as e:
        fc_log("antenna_html_report", f'❌ Erro ao gerar PDF: {e}')
        fc_log("antenna_html_report", f'📄 Apenas HTML gerado: {html_result}')
    
    return results


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