import sys
import os
from datetime import datetime

def generate_html_report(pcap_path, all_analysis_data, output_path=None):
    """
    Generates a full HTML report from the analysis data.
    """
    pcap_filename = os.path.basename(pcap_path)
    current_datetime = datetime.now().strftime("%d-%m-%Y %H:%M:%S")

    html_content = f"""
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Network Report by pcapana</title>
        <style>
            body {{ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; margin: 20px; color: #333; font-size: 14px; }}
            .container {{ max-width: 1200px; margin: auto; }}
            h1 {{ color: #2c3e50; border-bottom: 2px solid #ddd; padding-bottom: 5px; }}
            h2 {{ color: #34495e; border-bottom: 1px solid #ddd; padding-bottom: 5px; }}
            pre {{ background: #f4f4f4; padding: 10px; border-radius: 5px; overflow-x: auto; font-size: 13px; }}
            .section {{ margin-bottom: 40px; }}
            footer {{ text-align: center; margin-top: 50px; color: #7f8c8d; }}
            table {{ width: 100%; border-collapse: collapse; margin-top: 15px; border: 1px solid #ddd; font-size: 13px; }}
            th, td {{ padding: 12px; text-align: left; border-bottom: 1px solid #ddd; }}
            th {{ background-color: #f2f2f2; font-weight: bold; }}
            tr:hover {{ background-color: #f5f5f5; }}
            .note {{ font-style: italic; color: #7f8c8d; margin-top: 5px; }}
        </style>
    </head>
    <body>
        <div class="container">
            <h1>Network Report by pcapana</h1>
            <p><strong>File Name:</strong> {pcap_filename}</p>
            <p><strong>Generated on:</strong> {current_datetime}</p>
    """

    for title, analysis_data in all_analysis_data.items():
        headers = analysis_data['headers']
        data_rows = analysis_data['data']

        table_rows_html = ""
        for row in data_rows:
            cell_html = "".join([f"<td>{row.get(header, '')}</td>" for header in headers])
            table_rows_html += f"<tr>{cell_html}</tr>"

        html_content += f"""
            <div class="section">
                <h2>{title}</h2>
                <table>
                    <thead>
                        <tr>
                            {''.join([f"<th>{header}</th>" for header in headers])}
                        </tr>
                    </thead>
                    <tbody>
                        {table_rows_html}
                    </tbody>
                </table>
        """
        if title == "Protocol Statistics":
            total_packets = sum(int(row["Count"]) for row in data_rows if str(row.get("Count", "")).isdigit())
            html_content += f"""
                <p class="note"><strong>Total Packets:</strong> {total_packets}</p>
            """
        
        if title == "Visited Domains":
            html_content += f"""
                <p class="note"><strong>Note:</strong> This analysis includes websites directly visited by the user as well as domains accessed by background applications and services running on the machine.</p>
            """
        
        if title == "OSI Layer Analysis":
            html_content += f"""
                <p class="note"><strong>Note:</strong> A single packet can contain protocols from multiple layers, so a packet is counted in each layer it traverses. For example, an HTTP packet is counted in Layer 7, Layer 4, and Layer 3.</p>
            """
        
        # if title == "Port Analysis":
        #     html_content += f"""
        #         <p class="note"><strong>Total Unique Local IPs in Capture:</strong> {len(analysis_data.get('total_ips', []))}</p>
        #         <p class="note"><strong>Note:</strong> A single local IP can communicate with multiple unique remote ports.</p>
        #     """
        
        html_content += """
            </div>
        """
    
    html_content += f"""
        </div>
        <footer>
            <p>Report generated by <a href="https://github.com/12hms12/pcapana" target="_blank">pcapana</a>.</p>
        </footer>
    </body>
    </html>
    """

    if output_path is None:
        report_name = os.path.splitext(pcap_filename)[0] + "_pcapana.html"
    else:
        report_name = output_path
        
    with open(report_name, "w") as f:
        f.write(html_content)
    
    print(f"\n\n***HTML report saved to {report_name}***")