"""soagila_receipt — View and query decision receipts from the IDL."""

import json
from mcp.types import Tool, TextContent


def get_definition() -> Tool:
    return Tool(
        name="soagila_receipt",
        description=(
            "View decision receipts from the Immutable Decision Ledger (IDL). "
            "Every SOAGILA operation creates a cryptographic receipt recording "
            "which memories were accessed, what reasoning was used, and the "
            "Merkle hash chain for tamper detection. Call this when the user "
            "asks about audit trails, compliance proof, or wants to understand "
            "why past decisions were made. Present results in a human-friendly "
            "format — not raw JSON."
        ),
        inputSchema={
            "type": "object",
            "properties": {
                "receipt_id": {"type": "string", "description": "Specific receipt ID to view."},
                "receipt_type": {
                    "type": "string",
                    "enum": ["query", "store", "promote", "arbitrate", "annihilate"],
                    "description": "Filter by receipt type.",
                },
                "limit": {
                    "type": "integer", "minimum": 1, "maximum": 100,
                    "description": "Maximum receipts to return. Default: 20",
                },
            },
        },
    )


async def handle(arguments: dict) -> list[TextContent]:
    receipt_id = arguments.get("receipt_id")
    receipt_type = arguments.get("receipt_type")
    limit = arguments.get("limit", 20)

    from soagila.core.idl.ledger import get_receipt, get_receipts, verify_chain, get_chain_length

    if receipt_id:
        # Single receipt lookup
        r = await get_receipt(receipt_id)
        if r is None:
            return [TextContent(type="text", text=json.dumps({"error": f"Receipt {receipt_id} not found."}))]
        result = {
            "receipt": {
                "id": r.id, "type": r.receipt_type,
                "memories_accessed": r.memories_accessed,
                "memories_created": r.memories_created,
                "merkle_hash": r.merkle_hash,
                "prev_merkle_hash": r.prev_merkle_hash,
                "created_at": str(r.created_at),
                "metadata": r.metadata,
            },
        }
    else:
        # List receipts
        receipts = await get_receipts(
            user_id="local", receipt_type=receipt_type, limit=limit,
        )
        chain = await verify_chain()
        result = {
            "receipts": [
                {
                    "id": r.id, "type": r.receipt_type,
                    "memories_accessed": len(r.memories_accessed),
                    "memories_created": len(r.memories_created),
                    "merkle_hash": r.merkle_hash[:16] + "...",
                    "created_at": str(r.created_at),
                }
                for r in receipts
            ],
            "chain_length": get_chain_length(),
            "chain_valid": chain["valid"],
        }

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