import json
import os
import logging
from typing import List, Dict, Any
from datetime import datetime

# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

def analyze_ralph_stories(tasks_file: str, output_file: str) -> None:
    """
    Analyzes completed Ralph stories from a JSON file, calculates success patterns,
    average completion time, and cost per story, and saves the insights to a JSON file.

    Args:
        tasks_file (str): The path to the JSON file containing the Ralph tasks.
        output_file (str): The path to the JSON file where the analysis results will be saved.
    """

    try:
        with open(tasks_file, 'r') as f:
            tasks: List[Dict[str, Any]] = json.load(f)
    except FileNotFoundError:
        logging.error(f"File not found: {tasks_file}")
        return
    except json.JSONDecodeError:
        logging.error(f"Invalid JSON in file: {tasks_file}")
        return

    completed_stories: List[Dict[str, Any]] = [task for task in tasks if task.get("passes") == True]
    total_stories: int = len(tasks)
    successful_stories: int = len(completed_stories)

    total_completion_time: float = 0.0
    valid_completion_times: int = 0
    total_cost: float = 0.0
    valid_costs: int = 0

    for story in completed_stories:
        # Calculate completion time
        start_time_str: str = story.get("start_time")
        end_time_str: str = story.get("end_time")

        if start_time_str and end_time_str:
            try:
                start_time: datetime = datetime.fromisoformat(start_time_str.replace('Z', '+00:00'))
                end_time: datetime = datetime.fromisoformat(end_time_str.replace('Z', '+00:00'))
                completion_time: float = (end_time - start_time).total_seconds()
                total_completion_time += completion_time
                valid_completion_times += 1
            except (ValueError, TypeError) as e:
                logging.error(f"Error calculating completion time for story: {story.get('title', 'Unnamed Story')}. Error: {e}")
        else:
            logging.warning(f"Missing start or end time for story: {story.get('title', 'Unnamed Story')}")


        # Calculate cost
        actual_cost: float = story.get("actual_cost")
        estimated_cost: float = story.get("estimated_cost")

        if actual_cost is not None:
            try:
                total_cost += float(actual_cost)
                valid_costs += 1
            except ValueError:
                logging.error(f"Invalid actual_cost value for story: {story.get('title', 'Unnamed Story')}")

        elif estimated_cost is not None:
            try:
                total_cost += float(estimated_cost)
                valid_costs += 1
            except ValueError:
                logging.error(f"Invalid estimated_cost value for story: {story.get('title', 'Unnamed Story')}")
        else:
            logging.warning(f"Missing cost information for story: {story.get('title', 'Unnamed Story')}")

    # Calculate Averages
    average_completion_time: float = (total_completion_time / valid_completion_times) if valid_completion_times > 0 else 0
    average_cost: float = (total_cost / valid_costs) if valid_costs > 0 else 0
    success_rate: float = (successful_stories / total_stories) if total_stories > 0 else 0

    analytics: Dict[str, float] = {
        "success_rate": success_rate,
        "average_completion_time": average_completion_time,
        "average_cost": average_cost,
        "total_stories": total_stories,
        "successful_stories": successful_stories
    }

    try:
        os.makedirs(os.path.dirname(output_file), exist_ok=True) # Ensure directory exists
        with open(output_file, 'w') as outfile:
            json.dump(analytics, outfile, indent=4)
        logging.info(f"Analysis saved to: {output_file}")

    except OSError as e:
        logging.error(f"Error writing to file: {output_file}. Error: {e}")
    except TypeError as e:
         logging.error(f"Type error during JSON serialization: {e}")



# Define file paths
tasks_file: str = "/mnt/e/genesis-system/loop/tasks.json"
output_file: str = "/mnt/e/genesis-system/data/ralph_analytics.json"

# Run the analysis
analyze_ralph_stories(tasks_file, output_file)