from jycm.helper import dump_html_output
from jycm.jycm import YouchamaJsonDiffer
import os
import uuid
import json
from typing import Tuple
import logging

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def compare_configurations(config_a_data: dict, config_b_data: dict) -> Tuple[dict, str, str]:
    """
    Compare two configurations using jycm and return the differences along with the HTML report path and JSON diff path.
    """
    # Initialize the JSON differ
    ycm = YouchamaJsonDiffer(config_a_data, config_b_data)
    
    # Get the differences
    diff_result = ycm.get_diff()
    
    # Generate a unique directory for the HTML and JSON report inside 'reports'
    report_uuid = uuid.uuid4().hex
    reports_dir = "reports"
    report_dir = os.path.join(reports_dir, f"diff_report_{report_uuid}")
    
    # Ensure the main 'reports' directory exists
    os.makedirs(reports_dir, exist_ok=True)
    
    try:
        # Dump the HTML output into the unique directory
        dump_html_output(config_a_data, config_b_data, diff_result, report_dir)
        
        # Also dump the JSON diff into a file
        json_diff_path = os.path.join(report_dir, f"diff_report_{report_uuid}.json")
        with open(json_diff_path, 'w', encoding='utf-8') as json_file:
            json.dump(diff_result, json_file, indent=4)
    except FileExistsError:
        logger.error(f"Report directory {report_dir} already exists.")
        raise
    
    # Path to the index.html
    report_path = os.path.join(report_dir, "index.html")
    
    # Fix resource paths in the HTML file
    fix_resource_paths(report_path, report_uuid)
    
    logger.info(f"Generated diff report at {report_path} and JSON diff at {json_diff_path}")
    
    return diff_result, report_path, json_diff_path

def fix_resource_paths(report_path: str, report_uuid: str) -> None:
    """
    Modify the resource paths in index.html to be relative.
    """
    try:
        with open(report_path, 'r', encoding='utf-8') as file:
            html_content = file.read()
        
        # Replace 'reports/diff_report_<uuid>/' with './'
        old_path = f"reports/diff_report_{report_uuid}/"
        new_path = "./"
        updated_html = html_content.replace(old_path, new_path)
        
        with open(report_path, 'w', encoding='utf-8') as file:
            file.write(updated_html)
        
        logger.info(f"Fixed resource paths in {report_path}")
    except Exception as e:
        logger.error(f"Error fixing resource paths: {e}")
        raise

def generate_summary(report_path: str) -> str:
    """
    Placeholder for summary generation (to be implemented with OpenAI API later).
    """
    return "Summary generation not implemented yet."

implement open ai function that takes the json diff file generated as input , open ai api allow to use jsonl files i belive , implement that
here is the prompt t use "I have a JSON diff that highlights the differences between the configurations of two Kubernetes clusters. "
            "This diff contains changes in key components such as pods, deployments, replicas, containers, and networking configurations.\n"
            "I need a concise yet detailed summary of the following:\n"
            "- Key Differences: Summarize the major configuration changes.\n"
            "- Potential Issues: Identify potential misconfigurations or inconsistencies.\n"
            "- Impact on Environment: How might these differences impact the clusters?\n"
            "- Suggestions for Resolution: Provide insights to resolve these issues.\n"