"""soagila_backup — Create and restore encrypted backups."""

import json
from mcp.types import Tool, TextContent


def get_definition() -> Tool:
    return Tool(
        name="soagila_backup",
        description=(
            "Create or restore encrypted backups of the project memory database. "
            "Backups are AES-256-GCM encrypted and stored locally at ~/.soagila/backups/. "
            "Use action='create' to backup, action='restore' to restore, "
            "action='list' to see available backups. Pro tier: auto-backup on startup."
        ),
        inputSchema={
            "type": "object",
            "properties": {
                "action": {
                    "type": "string",
                    "enum": ["create", "restore", "list"],
                    "description": "Action: create a backup, restore from backup, or list backups.",
                },
                "filename": {
                    "type": "string",
                    "description": "For restore: specific backup filename. Omit for most recent.",
                },
            },
            "required": ["action"],
        },
    )


async def handle(arguments: dict) -> list[TextContent]:
    action = arguments.get("action", "list")
    filename = arguments.get("filename")

    from soagila.core.backup import create_backup, restore_backup, list_backups

    if action == "create":
        result = await create_backup()
    elif action == "restore":
        result = await restore_backup(filename)
    elif action == "list":
        backups = list_backups()
        result = {
            "backups": [
                {
                    "filename": b["filename"],
                    "timestamp": b["timestamp"],
                    "original_size_kb": b.get("original_size_kb", 0),
                    "encrypted_size_kb": b.get("encrypted_size_kb", 0),
                    "exists": b.get("exists", False),
                }
                for b in backups
            ],
            "count": len(backups),
        }
    else:
        result = {"error": f"Unknown action: {action}"}

    return [TextContent(type="text", text=json.dumps(result, indent=2))]
