#!/usr/bin/env python3
"""Generate an HTML dashboard from code_repair_logs SQLite database."""

import json
import sqlite3
import webbrowser
from pathlib import Path


def main():
    db_path = Path(__file__).parent / "code_repair_log.db"
    cf_db_path = Path(__file__).parent / "code_repair_logs_cf.db"
    template_path = Path(__file__).parent / "code_repair_dashboard.html"
    output_path = Path(__file__).parent / "code_repair_dashboard_live.html"

    # Connect to main database and fetch all logs
    conn = sqlite3.connect(db_path)
    conn.row_factory = sqlite3.Row
    cursor = conn.cursor()

    cursor.execute("""
        SELECT optimization_id, trace_id, user_prompt, explanation,
               refined_optimization, created_at, updated_at
        FROM code_repair_logs
        ORDER BY created_at DESC
    """)

    rows = cursor.fetchall()
    conn.close()

    # Connect to cf database and fetch passed/faster status
    cf_conn = sqlite3.connect(cf_db_path)
    cf_conn.row_factory = sqlite3.Row
    cf_cursor = cf_conn.cursor()

    cf_cursor.execute("""
        SELECT optimization_id, passed, faster
        FROM code_repair_logs_cf
    """)

    cf_rows = cf_cursor.fetchall()
    cf_conn.close()

    # Create lookup dict for cf data
    cf_data = {row["optimization_id"]: {"passed": row["passed"], "faster": row["faster"]} for row in cf_rows}

    # Convert to list of dicts and merge cf data
    data = []
    for row in rows:
        d = dict(row)
        opt_id = d["optimization_id"][:-4] + "cdrp"
        if opt_id in cf_data:
            d["passed"] = cf_data[opt_id]["passed"]
            d["faster"] = cf_data[opt_id]["faster"]
        else:
            d["passed"] = None
            d["faster"] = None
        data.append(d)

    # Read template
    template = template_path.read_text()

    # Replace placeholder with actual data
    json_data = json.dumps(data, default=str, indent=2)
    html_content = template.replace("DATA_PLACEHOLDER", json_data)

    # Write output
    output_path.write_text(html_content)

    print(f"Dashboard generated: {output_path}")
    print(f"Total logs: {len(data)}")
    print(f"Unique traces: {len(set(d['trace_id'] for d in data))}")

    # Open in browser
    webbrowser.open(f"file://{output_path.absolute()}")


if __name__ == "__main__":
    main()
