import json
import os

name = "user_notes"
description = (
    "Save, retrieve, and list personal notes specifically about the user. "
    "Use this to store facts, preferences, or important context about the user for future reference."
)
parameters = {
    "type": "object",
    "properties": {
        "action": {
            "type": "string",
            "enum": ["save", "get", "list", "delete"],
            "description": "The action to perform: 'save' a new note, 'get' a note by key, 'list' all saved note keys, or 'delete' a note by key."
        },
        "key": {
            "type": "string",
            "description": "The unique identifier (key) for the note (required for get, delete)."
        },
        "value": {
            "type": "string",
            "description": "The content of the note (required for 'save' action)."
        },
    },
    "required": ["action"],
}

# Define the file path for data persistence within the tool's directory
DATA_FILE = os.path.join(os.path.dirname(__file__), "user_notes_data.json")

def _load_data():
    """Loads data from the JSON file."""
    if os.path.exists(DATA_FILE):
        try:
            with open(DATA_FILE, "r", encoding="utf-8") as f:
                return json.load(f)
        except json.JSONDecodeError:
            # Handle case where file exists but is corrupted
            return {}
    return {}

def _save_data(data):
    """Saves data to the JSON file."""
    with open(DATA_FILE, "w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

async def execute(params: dict) -> str:
    action = params.get("action")
    data = _load_data()

    if action == "save":
        key = params.get("key")
        value = params.get("value")
        if not key or not value:
            raise ValueError("For 'save' action, both 'key' and 'value' must be provided.")
        
        data[key] = value
        _save_data(data)
        return f"Successfully saved note with key: {key}"

    elif action == "get":
        key = params.get("key")
        if not key:
            raise ValueError("For 'get' action, the 'key' parameter is required.")
        
        if key not in data:
            raise KeyError(f"Note with key '{key}' not found. Use 'list' to see available keys.")
        
        return data[key]

    elif action == "list":
        if not data:
            return "No user notes have been saved yet."
        keys = list(data.keys())
        return f"User notes available. Keys: {', '.join(keys)}"

    elif action == "delete":
        key = params.get("key")
        if not key:
            raise ValueError("For 'delete' action, the 'key' parameter is required.")
        
        if key in data:
            del data[key]
            _save_data(data)
            return f"Successfully deleted note with key: {key}"
        else:
            raise KeyError(f"Cannot delete. Note with key '{key}' not found.")

    else:
        raise ValueError(f"Invalid action specified: {action}. Must be one of: save, get, list, delete.")