import json
import argparse
import os
from datetime import datetime

HTML_TEMPLATE = """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CASSIA Hypothesis Generation Report</title>
    <style>
        body {{
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            line-height: 1.6;
            color: #333;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f9f9f9;
        }}
        h1, h2 {{
            color: #2c3e50;
            border-bottom: 2px solid #3498db;
            padding-bottom: 10px;
        }}
        .report-header {{
            text-align: center;
            margin-bottom: 40px;
        }}
        .report-header p {{
            font-size: 1.1em;
            color: #555;
        }}
        .cluster-section {{
            background-color: #ffffff;
            border: 1px solid #e1e1e1;
            border-radius: 8px;
            padding: 25px;
            margin-bottom: 30px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.05);
        }}
        table {{
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }}
        th, td {{
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }}
        th {{
            background-color: #3498db;
            color: white;
        }}
        tr:nth-child(even) {{
            background-color: #f2f2f2;
        }}
        tr:hover {{
            background-color: #eaf5ff;
        }}
        details {{
            margin-top: 20px;
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 10px;
        }}
        summary {{
            font-weight: bold;
            cursor: pointer;
            color: #3498db;
        }}
        pre {{
            background-color: #2c3e50;
            color: #f8f8f2;
            padding: 15px;
            border-radius: 4px;
            white-space: pre-wrap;
            word-wrap: break-word;
            font-family: "Courier New", Courier, monospace;
        }}
        .footer {{
            text-align: center;
            margin-top: 40px;
            font-size: 0.9em;
            color: #777;
        }}
    </style>
</head>
<body>
    <div class="report-header">
        <h1>CASSIA Hypothesis Generation Report</h1>
        <p>Generated on: {generation_date}</p>
        <p>Source file: {source_file}</p>
    </div>

    {cluster_reports}

    <div class="footer">
        <p>Report generated by CASSIA.</p>
    </div>
</body>
</html>
"""

CLUSTER_TEMPLATE = """
<div class="cluster-section">
    <h2>Cluster: {cluster_name}</h2>
    <h3>Top Hypotheses</h3>
    <table>
        <thead>
            <tr>
                <th>Rank</th>
                <th>Predicted Cell Type</th>
                <th>Reasoning</th>
            </tr>
        </thead>
        <tbody>
            {hypotheses_rows}
        </tbody>
    </table>
    <details>
        <summary>View Raw LLM Output</summary>
        <pre>{raw_response}</pre>
    </details>
</div>
"""

def create_html_report(json_path: str, report_path: str):
    """
    Generates an HTML report from a JSON file of hypothesis generation results.

    Args:
        json_path: Path to the input JSON file.
        report_path: Path to save the output HTML report.
    """
    if not os.path.exists(json_path):
        print(f"Error: JSON file not found at {json_path}")
        return

    with open(json_path, 'r', encoding='utf-8') as f:
        data = json.load(f)

    cluster_reports_html = ""
    for cluster_name, results in sorted(data.items()):
        parsed_data = results.get("parsed_response", [])
        raw_response = results.get("raw_response", "N/A")

        hypotheses_rows_html = ""
        if parsed_data and "error" not in parsed_data[0]:
            for item in parsed_data:
                hypotheses_rows_html += f"""
                <tr>
                    <td>{item.get('rank', 'N/A')}</td>
                    <td>{item.get('cell_type', 'N/A')}</td>
                    <td>{item.get('reasoning', 'N/A')}</td>
                </tr>
                """
        else:
            error_msg = parsed_data[0].get('error', 'Unknown error') if parsed_data else "No response"
            hypotheses_rows_html = f'<tr><td colspan="3">Error processing this cluster: {error_msg}</td></tr>'

        cluster_reports_html += CLUSTER_TEMPLATE.format(
            cluster_name=cluster_name,
            hypotheses_rows=hypotheses_rows_html,
            raw_response=raw_response
        )

    full_html = HTML_TEMPLATE.format(
        generation_date=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        source_file=os.path.basename(json_path),
        cluster_reports=cluster_reports_html
    )

    with open(report_path, 'w', encoding='utf-8') as f:
        f.write(full_html)
    
    print(f"Successfully generated HTML report at: {report_path}")

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description="Generate an HTML report from CASSIA hypothesis generation results."
    )
    parser.add_argument(
        "json_file",
        type=str,
        help="Path to the input JSON file from hypothesis_generation.py."
    )
    parser.add_argument(
        "-o", "--output",
        type=str,
        default="hypothesis_report.html",
        help="Path to save the output HTML report file (default: hypothesis_report.html)."
    )
    args = parser.parse_args()

    create_html_report(args.json_file, args.output) 