import csv
import os

def csv_to_latex_booktabs(input_file, output_file):
    # Read the CSV file
    with open(input_file, 'r') as csvfile:
        reader = csv.DictReader(csvfile)
        data = list(reader)

    # Sort the data alphabetically by Dataset name
    data.sort(key=lambda x: x['Dataset'].lower())

    # Prepare the LaTeX table content
    latex_content = [
        "\\begin{table*}[!ht]",
        "\\centering",
        "\\caption{Dataset statistics.}",
        "\\label{tab:dataset-statistics}",
        "\\begin{tabular}{lrrrrr}",
        "\\toprule",
        # "Dataset & Instances & Attributes & Class 0 & Class 1 & Class Ratio \\\\"
        "Dataset & \# Examples & \# Features & Class 0 & Class 1 & Class Ratio \\\\"
    ]

    latex_content.append("\\midrule")

    for row in data:
        class_0 = int(row['Class 0 Examples'])
        class_1 = int(row['Class 1 Examples'])
        class_ratio = round(class_1 / class_0, 2) if class_0 != 0 else 'N/A'
        
        latex_row = " & ".join([
            row['Dataset'].replace('_', '\\_'),
            row['Instances'],
            row['Attributes'],
            f"{class_0}",
            f"{class_1}",
            f"{class_ratio}"
        ])
        latex_content.append(latex_row + " \\\\")

    latex_content.extend([
        "\\bottomrule",
        "\\end{tabular}",
        "\\end{table*}"
    ])

    # Write the LaTeX table to a file
    with open(output_file, 'w') as latexfile:
        latexfile.write("\n".join(latex_content))

# File paths
input_file = "results/dataset_statistics.csv"
output_file = "results/dataset_statistics_table.tex"

# Convert CSV to LaTeX table
csv_to_latex_booktabs(input_file, output_file)

print(f"LaTeX table has been generated and saved to {output_file}")

