os.makedirs(dst, exist_ok=dirs_exist_ok)
  File "<frozen os>", line 225, in makedirs
FileExistsError: [Errno 17] File exists: 'reports/diff_report_3995fee14bae4587baf8faa6f5f6f8cf'

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

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

# OpenAI API key (set this securely, consider using an environment variable)
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
openai.api_key = OPENAI_API_KEY


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 and handle it if the directory already exists
    if os.path.exists(report_dir):
        logger.warning(f"Directory {report_dir} already exists. Clearing and recreating it...")
        shutil.rmtree(report_dir)  # Remove the existing directory

    os.makedirs(report_dir)

    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)

        # Generate OpenAI Summary and save it to a text file
        # Fix: load the diff from the saved JSON diff path before passing it to generate_summary
        with open(json_diff_path, 'r') as json_file:
            diff_json = json.load(json_file)
        
        summary_file_path = generate_summary(diff_json, report_dir)

    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}, JSON diff at {json_diff_path}, and summary at {summary_file_path}")

    return diff_result, report_path, json_diff_path


def generate_summary(diff_json: dict, report_dir: str) -> str:
    """
    Uploads the JSON diff as a JSONL file to OpenAI and generates a summary.
    The summary is saved as a text file in the report directory.
    """
    try:
        # Convert JSON to JSONL format and save it to a file
        jsonl_file_path = os.path.join(report_dir, 'diff_report.jsonl')
        with open(jsonl_file_path, 'w') as jsonl_file:
            jsonl_file.write(json.dumps(diff_json) + '\n')  # Each line should be a JSON object

        # Upload the JSONL file to OpenAI
        uploaded_file = openai.File.create(
            file=open(jsonl_file_path, 'rb'),  # Open the JSONL file
            purpose='answers'  # Adjust based on the purpose you're using
        )

        # Use the uploaded file for generating a summary
        prompt = (
            "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"
        )

        # Call OpenAI API to process the JSONL file and get a summary
        response = openai.Completion.create(
            model="gpt-4",  # Or any other model you want to use
            prompt=prompt,
            file=uploaded_file['id'],  # Use the file ID for processing
            max_tokens=1500,  # Adjust the token count based on the expected response length
        )

        # Extract the summary from the response
        summary = response['choices'][0]['text']

        # Save the summary to a text file in the report directory
        summary_file = os.path.join(report_dir, 'summary.txt')
        with open(summary_file, 'w', encoding='utf-8') as f:
            f.write(summary)

        logger.info(f"Generated summary and saved to {summary_file}")
        return summary_file

    except Exception as e:
        logger.error(f"Error generating summary: {e}")
        return f"Error generating summary: {e}"


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