"""soagila_inspect — View detailed memory information."""

import json
from mcp.types import Tool, TextContent


def get_definition() -> Tool:
    return Tool(
        name="soagila_inspect",
        description=(
            "Inspect a specific memory in detail: content, tier, decay "
            "timeline, access history, related memories, and graph "
            "relationships. Useful for debugging memory behavior or "
            "understanding how information flows through the cognitive system."
        ),
        inputSchema={
            "type": "object",
            "properties": {
                "memory_id": {
                    "type": "string",
                    "description": "The UUID of the memory to inspect.",
                },
            },
            "required": ["memory_id"],
        },
    )


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

    # Try episodic first
    from soagila.core.tcmg.episodic_memory import get as ep_get, get_related
    mem = await ep_get(memory_id)

    if mem is None:
        return [TextContent(type="text", text=json.dumps({
            "error": f"Memory '{memory_id}' not found.",
            "hint": "Use soagila_recall first to find memory IDs.",
        }))]

    # Get related memories
    related = await get_related(memory_id, depth=2)

    # Calculate current decay
    from soagila.core.tcmg.decay_engine import calculate_relevance
    from datetime import datetime, timezone
    now = datetime.now(timezone.utc)
    created = mem.created_at
    if isinstance(created, str):
        created = datetime.fromisoformat(created)
    if created.tzinfo is None:
        created = created.replace(tzinfo=timezone.utc)

    last_acc = mem.last_accessed
    if isinstance(last_acc, str):
        last_acc = datetime.fromisoformat(last_acc)
    if last_acc and last_acc.tzinfo is None:
        last_acc = last_acc.replace(tzinfo=timezone.utc)

    current_relevance = calculate_relevance(
        created_at=created, stability=mem.stability,
        decay_rate=mem.decay_rate, access_count=mem.access_count,
        last_accessed=last_acc, now=now,
    )

    result = {
        "memory": {
            "id": mem.id,
            "content": mem.content,
            "tier": mem.tier,
            "topic_tags": mem.topic_tags,
            "classification": mem.classification,
            "source_type": mem.source_type,
            "created_at": str(mem.created_at),
        },
        "decay": {
            "current_relevance": round(current_relevance, 4),
            "stored_relevance": mem.relevance_score,
            "stability": mem.stability,
            "decay_rate": mem.decay_rate,
            "is_decayed": mem.is_decayed,
        },
        "access": {
            "count": mem.access_count,
            "last_accessed": str(mem.last_accessed) if mem.last_accessed else None,
        },
        "security": {
            "is_canary": mem.is_canary,
            "pii_tags": mem.pii_tags,
        },
        "related_memories": [
            {"id": r.id, "content": r.content[:80], "topic_tags": r.topic_tags}
            for r in related[:5]
        ],
    }

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