#!/usr/bin/env python3
"""
Convert benchmark results CSV to an HTML table for the documentation.
"""

import os
import sys
import csv
import argparse
from pathlib import Path


def convert_csv_to_html_table(csv_path, output_path=None):
    """
    Convert a CSV file to an HTML table.

    Parameters:
    -----------
    csv_path : str
        Path to the CSV file
    output_path : str, optional
        Path for the HTML output file. If None, will output to stdout.
    """
    # Read CSV data
    with open(csv_path, "r") as csvfile:
        reader = csv.reader(csvfile)
        headers = next(reader)  # Get headers
        rows = list(reader)  # Get all rows

    # Create HTML table
    html = ['<table class="benchmark-table">']

    # Add header row
    html.append("<thead>")
    html.append("<tr>")
    for header in headers:
        html.append(f"<th>{header}</th>")
    html.append("</tr>")
    html.append("</thead>")

    # Add data rows
    html.append("<tbody>")
    for row in rows:
        html.append("<tr>")
        # Format cell based on content type
        for i, cell in enumerate(row):
            # For the first column (Format), use regular text
            if i == 0:
                html.append(f"<td>{cell}</td>")
            else:
                # For numeric columns, right-align
                try:
                    value = float(cell)
                    # Use scientific notation for very small values
                    if value < 0.0001 and value != 0:
                        formatted = f"{value:.6e}"
                    else:
                        formatted = cell
                    html.append(f'<td class="numeric">{formatted}</td>')
                except ValueError:
                    # Non-numeric values (like N/A)
                    html.append(f"<td>{cell}</td>")
        html.append("</tr>")
    html.append("</tbody>")

    html.append("</table>")

    # Add CSS for styling
    css = """
<style>
.benchmark-table {
    border-collapse: collapse;
    width: 100%;
    margin-bottom: 20px;
}
.benchmark-table th {
    background-color: #f2f2f2;
    text-align: left;
    padding: 8px;
    border: 1px solid #ddd;
}
.benchmark-table td {
    padding: 8px;
    border: 1px solid #ddd;
}
.benchmark-table .numeric {
    text-align: right;
}
.benchmark-table tr:nth-child(even) {
    background-color: #f9f9f9;
}
.benchmark-table tr:hover {
    background-color: #f1f1f1;
}
</style>
"""

    # Combine CSS and table
    full_html = css + "\n".join(html)

    # Output
    if output_path:
        with open(output_path, "w") as f:
            f.write(full_html)
    else:
        print(full_html)

    return full_html


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Convert CSV to HTML table")
    parser.add_argument("csv_file", help="CSV file to convert")
    parser.add_argument("--output", "-o", help="Output HTML file (default: stdout)")
    args = parser.parse_args()

    convert_csv_to_html_table(args.csv_file, args.output)
