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

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

def build_knowledge_graph(task_results_path: str, output_path: str) -> None:
    """
    Reads completed task results from a JSON file, builds a knowledge graph
    of Genesis capabilities, and stores the graph in a JSON file.

    Args:
        task_results_path: Path to the JSON file containing task results.
        output_path: Path to the output JSON file for the knowledge graph.
    """
    try:
        with open(task_results_path, 'r') as f:
            task_results: List[Dict[str, Any]] = json.load(f)
    except FileNotFoundError:
        logging.error(f"Task results file not found: {task_results_path}")
        return
    except json.JSONDecodeError:
        logging.error(f"Error decoding JSON in: {task_results_path}")
        return
    except Exception as e:
        logging.error(f"An unexpected error occurred while reading task results: {e}")
        return

    knowledge_graph: Dict[str, List[str]] = {}
    for task in task_results:
        if task.get("passes") == True: # Only include completed tasks
            task_name = task.get("title", "Unknown Task")
            task_description = task.get("Description", "No Description")

            knowledge_graph[task_name] = [task_description]

    try:
        os.makedirs(os.path.dirname(output_path), exist_ok=True)
        with open(output_path, 'w') as f:
            json.dump(knowledge_graph, f, indent=4)
        logging.info(f"Knowledge graph successfully built and saved to: {output_path}")
    except Exception as e:
        logging.error(f"Error writing knowledge graph to file: {e}")


if __name__ == '__main__':
    TASK_RESULTS_PATH = "/mnt/e/genesis-system/loop/tasks.json"
    OUTPUT_PATH = "/mnt/e/genesis-system/KNOWLEDGE_GRAPH/capabilities.json"
    build_knowledge_graph(TASK_RESULTS_PATH, OUTPUT_PATH)