"""
Phase 79: Knowledge MCP Microservice Tools.

Exposes the Phase 59 Knowledge Graph as MCP tools that can run
either as a plugin in the monolith or as a standalone MCP server.
"""

from mcp.types import TextContent, Tool, ToolAnnotations

_SAFE_READ = ToolAnnotations(readOnlyHint=True, destructiveHint=False, idempotentHint=True, openWorldHint=False)
_SAFE_WRITE = ToolAnnotations(readOnlyHint=False, destructiveHint=False, idempotentHint=False, openWorldHint=False)

TOOLS = [
    Tool(
        name="knowledge_store",
        description="Store a knowledge entry in the shared knowledge graph.",
        inputSchema={
            "type": "object",
            "properties": {
                "topic": {"type": "string", "description": "Short topic/title"},
                "content": {"type": "string", "description": "Knowledge content"},
                "author_id": {"type": "string", "description": "Who is storing this"},
                "tags": {"type": "array", "items": {"type": "string"}, "description": "Tags for discovery"},
                "category": {
                    "type": "string",
                    "enum": ["general", "architecture", "codebase", "process", "decision", "bug", "feature", "reference"],
                    "description": "Category (default: general)",
                },
                "confidence": {"type": "number", "description": "Confidence 0.0-1.0 (default: 1.0)"},
            },
            "required": ["topic", "content", "author_id"],
        },
        annotations=_SAFE_WRITE,
    ),
    Tool(
        name="knowledge_query",
        description="Search the knowledge graph by text query. Returns ranked results.",
        inputSchema={
            "type": "object",
            "properties": {
                "query": {"type": "string", "description": "Search query"},
                "category": {"type": "string", "description": "Filter by category"},
                "min_confidence": {"type": "number", "description": "Min confidence threshold"},
                "limit": {"type": "integer", "description": "Max results (default: 10)"},
            },
            "required": ["query"],
        },
        annotations=_SAFE_READ,
    ),
    Tool(
        name="knowledge_get",
        description="Get a specific knowledge entry by ID.",
        inputSchema={
            "type": "object",
            "properties": {
                "knowledge_id": {"type": "string"},
            },
            "required": ["knowledge_id"],
        },
        annotations=_SAFE_READ,
    ),
    Tool(
        name="knowledge_verify",
        description="Verify or dispute a knowledge entry. Adjusts confidence score.",
        inputSchema={
            "type": "object",
            "properties": {
                "knowledge_id": {"type": "string"},
                "verifier_id": {"type": "string"},
                "is_accurate": {"type": "boolean", "description": "True=verify, False=dispute"},
            },
            "required": ["knowledge_id", "verifier_id"],
        },
        annotations=_SAFE_WRITE,
    ),
    Tool(
        name="knowledge_context",
        description="Get relevant knowledge for a task description. Used by agents before acting.",
        inputSchema={
            "type": "object",
            "properties": {
                "task_description": {"type": "string"},
                "limit": {"type": "integer", "description": "Max results (default: 5)"},
            },
            "required": ["task_description"],
        },
        annotations=_SAFE_READ,
    ),
    Tool(
        name="knowledge_topics",
        description="List all knowledge topics, optionally by category.",
        inputSchema={
            "type": "object",
            "properties": {
                "category": {"type": "string", "description": "Filter by category"},
            },
        },
        annotations=_SAFE_READ,
    ),
    Tool(
        name="knowledge_stats",
        description="Get knowledge base statistics.",
        inputSchema={"type": "object", "properties": {}},
        annotations=_SAFE_READ,
    ),
]


# ── Handlers ───────────────────────────────────────────────────────────────

import json


async def _handle_store(args: dict) -> list[TextContent]:
    from brynq.knowledge_mcp import store_knowledge
    try:
        kid = store_knowledge(
            topic=args["topic"],
            content=args["content"],
            author_id=args["author_id"],
            tags=args.get("tags"),
            category=args.get("category", "general"),
            confidence=args.get("confidence", 1.0),
        )
        return [TextContent(type="text", text=f"Stored knowledge entry: {kid}")]
    except (ValueError, Exception) as e:
        return [TextContent(type="text", text=f"Error: {e}")]


async def _handle_query(args: dict) -> list[TextContent]:
    from brynq.knowledge_mcp import query_knowledge
    results = query_knowledge(
        query=args["query"],
        category=args.get("category"),
        min_confidence=args.get("min_confidence", 0.0),
        limit=args.get("limit", 10),
    )
    return [TextContent(type="text", text=json.dumps(results, indent=2, default=str))]


async def _handle_get(args: dict) -> list[TextContent]:
    from brynq.knowledge_mcp import get_knowledge
    entry = get_knowledge(args["knowledge_id"])
    if entry is None:
        return [TextContent(type="text", text="Not found")]
    return [TextContent(type="text", text=json.dumps(entry, indent=2, default=str))]


async def _handle_verify(args: dict) -> list[TextContent]:
    from brynq.knowledge_mcp import verify_knowledge
    try:
        entry = verify_knowledge(
            knowledge_id=args["knowledge_id"],
            verifier_id=args["verifier_id"],
            is_accurate=args.get("is_accurate", True),
        )
        action = "verified" if args.get("is_accurate", True) else "disputed"
        conf = entry.get("confidence", 0)
        return [TextContent(type="text", text=f"Entry {action}. New confidence: {conf:.2f}")]
    except (FileNotFoundError, ValueError) as e:
        return [TextContent(type="text", text=f"Error: {e}")]


async def _handle_context(args: dict) -> list[TextContent]:
    from brynq.knowledge_mcp import get_context_for_task
    results = get_context_for_task(
        task_description=args["task_description"],
        limit=args.get("limit", 5),
    )
    return [TextContent(type="text", text=json.dumps(results, indent=2, default=str))]


async def _handle_topics(args: dict) -> list[TextContent]:
    from brynq.knowledge_mcp import list_topics
    topics = list_topics(category=args.get("category"))
    return [TextContent(type="text", text=json.dumps(topics, indent=2, default=str))]


async def _handle_stats(args: dict) -> list[TextContent]:
    from brynq.knowledge_mcp import get_knowledge_stats
    stats = get_knowledge_stats()
    return [TextContent(type="text", text=json.dumps(stats, indent=2, default=str))]


HANDLERS = {
    "knowledge_store": _handle_store,
    "knowledge_query": _handle_query,
    "knowledge_get": _handle_get,
    "knowledge_verify": _handle_verify,
    "knowledge_context": _handle_context,
    "knowledge_topics": _handle_topics,
    "knowledge_stats": _handle_stats,
}
