import os
from pathlib import Path
from jinja2 import Environment, FileSystemLoader
import webbrowser
import json
import re

# --- Configuration ---
# Make paths absolute relative to the script's location for robustness
SCRIPT_DIR = Path(__file__).resolve().parent
RESULTS_DIR = SCRIPT_DIR / "results"
TEMPLATE_DIR = SCRIPT_DIR / "templates"
REPORT_FILE = SCRIPT_DIR / "report.html"
JSON_RESULTS_FILE = RESULTS_DIR / "results.json"

def generate_interactive_report():
    """
    Reads the structured results from a JSON file and renders the
    interactive HTML report.
    """
    # 1. Check if the JSON file exists
    if not JSON_RESULTS_FILE.is_file():
        print(f"Error: Results file '{JSON_RESULTS_FILE}' not found.")
        print("Please run the 'run_detection.py' script first to generate the results.")
        return

    # 2. Load the data from the JSON file
    with open(JSON_RESULTS_FILE, 'r', encoding='utf-8') as f:
        report_data = json.load(f)
    
    if not report_data.get("image_results"):
        print("Error: The results file is empty or has an invalid format.")
        return
        
    print(f"Loaded data for {len(report_data['image_results'])} images from {len(report_data['model_names'])} models.")

    # 3. Extract image prefixes for filtering
    image_names = report_data['image_results'].keys()
    # Extracts the non-numeric part at the start of the filename as the prefix
    image_prefixes = sorted(list(set(
        (re.match(r'([a-zA-Z_-]+)', name) or (None,)).group(1)
        for name in image_names
        if re.match(r'([a-zA-Z_-]+)', name)
    )))
    print(f"Found image prefixes: {image_prefixes}")

    # 4. Use Jinja2 to render the HTML file
    env = Environment(loader=FileSystemLoader(str(TEMPLATE_DIR)))
    template = env.get_template("report_template.html")
    # Pass only the necessary data to the template
    html_content = template.render(
        report_data=report_data,
        image_prefixes=image_prefixes
    )

    # 5. Write the report file
    with open(REPORT_FILE, "w", encoding="utf-8") as f:
        f.write(html_content)
        
    print(f"\n--- Interactive report generated successfully! ---")
    print(f"Report file saved at: {REPORT_FILE.resolve()}")
    
    # 5. Automatically open the report file in the browser
    try:
        webbrowser.open(f"file://{REPORT_FILE.resolve()}")
    except Exception as e:
        print(f"Could not automatically open the report in a browser: {e}")
        print("Please open the file manually.")

if __name__ == "__main__":
    generate_interactive_report() 