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

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

def analyze_revenue_pipeline(directory: str) -> List[Dict[str, Any]]:
    """
    Analyzes revenue pipeline context files in a directory, identifies actionable
    next steps, and creates a prioritized task list.

    Args:
        directory (str): The directory containing the revenue pipeline context files.

    Returns:
        List[Dict[str, Any]]: A prioritized list of tasks, where each task is a dictionary
                             containing 'priority', 'description', and 'rationale' keys.
                             Returns an empty list if no relevant files are found or
                             if an error occurs during processing.
    """
    task_list: List[Dict[str, Any]] = []
    try:
        for filename in os.listdir(directory):
            if filename.startswith("revenue_pipeline_") and filename.endswith(".json"):
                filepath = os.path.join(directory, filename)
                with open(filepath, 'r') as f:
                    try:
                        data = json.load(f)
                        # Example analysis (replace with actual logic based on file content)
                        if "key_metric" in data and data["key_metric"] < 100:
                            task_list.append({
                                "priority": 1,
                                "description": f"Improve key metric in {filename}",
                                "rationale": f"Key metric is below target ({data['key_metric']} < 100).",
                            })
                        elif "sales_stage" in data and data["sales_stage"] == "qualification":
                            task_list.append({
                                "priority": 2,
                                "description": f"Move sales stage forward in {filename}",
                                "rationale": f"Sales stage is currently in qualification for {filename}.",
                            })
                    except json.JSONDecodeError as e:
                        logging.error(f"Error decoding JSON from {filename}: {e}")
                    except Exception as e:
                        logging.error(f"Error processing {filename}: {e}")
    except FileNotFoundError:
        logging.error(f"Directory not found: {directory}")
    except Exception as e:
        logging.error(f"An unexpected error occurred: {e}")

    return task_list


def write_task_list_to_file(task_list: List[Dict[str, Any]], output_path: str) -> None:
    """
    Writes the prioritized task list to a JSON file.

    Args:
        task_list (List[Dict[str, Any]]): The prioritized task list.
        output_path (str): The path to the output file.
    """
    try:
        with open(output_path, 'w') as f:
            json.dump(task_list, f, indent=4)
        logging.info(f"Task list written to {output_path}")
    except Exception as e:
        logging.error(f"Error writing to file {output_path}: {e}")


def main() -> None:
    """
    Main function to execute the revenue pipeline analysis and write the task list to a file.
    """
    input_directory = "/mnt/e/genesis-system/REVENUE LAUNCH CONTEXT/"
    output_file = "/mnt/e/genesis-system/revenue_pipeline_tasks.json"

    task_list = analyze_revenue_pipeline(input_directory)
    write_task_list_to_file(task_list, output_file)

if __name__ == "__main__":
    main()