"""soagila_inherit — Memory Inheritance: cross-project semantic knowledge sharing."""

import json
from mcp.types import Tool, TextContent


def get_definition() -> Tool:
    return Tool(
        name="soagila_inherit",
        description=(
            "Memory Inheritance — manage cross-project semantic knowledge sharing. "
            "High-confidence, PII-clean semantic patterns automatically flow across "
            "projects via a shared global pool. Actions: "
            "'status' shows global pool stats, "
            "'list' shows inherited memories, "
            "'sync' forces promotion of local semantics to global pool, "
            "'lineage' traces a memory's origin. Requires Pro tier."
        ),
        inputSchema={
            "type": "object",
            "properties": {
                "action": {
                    "type": "string",
                    "enum": ["status", "list", "sync", "lineage"],
                    "description": (
                        "'status' — global pool stats and config. "
                        "'list' — browse global pool memories. "
                        "'sync' — re-evaluate all local semantics for global promotion. "
                        "'lineage' — trace a memory back to its source project."
                    ),
                },
                "memory_id": {
                    "type": "string",
                    "description": "Memory ID (for 'lineage' action).",
                },
                "source_project": {
                    "type": "string",
                    "description": "Filter by source project hash (for 'list' action).",
                },
                "limit": {
                    "type": "integer",
                    "minimum": 1,
                    "maximum": 100,
                    "description": "Max results for 'list'. Default: 20.",
                },
            },
            "required": ["action"],
        },
    )


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

    # Tier gate
    from soagila.project_manager import is_feature_allowed
    allowed, msg = is_feature_allowed("inheritance")
    if not allowed:
        return [TextContent(type="text", text=json.dumps({
            "error": msg,
            "upgrade_url": "https://soagila.com/pricing",
        }))]

    if action == "status":
        return await _handle_status()
    elif action == "list":
        return await _handle_list(arguments)
    elif action == "sync":
        return await _handle_sync()
    elif action == "lineage":
        return await _handle_lineage(arguments)
    else:
        return [TextContent(type="text", text=json.dumps({
            "error": f"Unknown action: {action}",
        }))]


async def _handle_status() -> list[TextContent]:
    from soagila.config import get_settings
    from soagila.core.inheritance.engine import get_global_stats

    settings = get_settings()
    stats = await get_global_stats()

    result = {
        "enabled": settings.inheritance_enabled,
        "confidence_threshold": settings.inheritance_confidence_threshold,
        "confidence_tax": settings.inheritance_confidence_tax,
        "max_global_results_per_recall": settings.inheritance_max_global_results,
        "global_pool": stats,
    }

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


async def _handle_list(arguments: dict) -> list[TextContent]:
    from soagila.db.sqlite_init import get_global_db

    source_project = arguments.get("source_project")
    limit = arguments.get("limit", 20)

    global_db = await get_global_db()

    if source_project:
        cursor = await global_db.execute(
            """SELECT id, source_project_hash, source_project_name, pattern_description,
                      confidence_score, original_confidence, inheritance_depth, inherited_at
               FROM global_semantic_memories
               WHERE source_project_hash = ?
               ORDER BY confidence_score DESC LIMIT ?""",
            (source_project, limit),
        )
    else:
        cursor = await global_db.execute(
            """SELECT id, source_project_hash, source_project_name, pattern_description,
                      confidence_score, original_confidence, inheritance_depth, inherited_at
               FROM global_semantic_memories
               ORDER BY confidence_score DESC LIMIT ?""",
            (limit,),
        )

    rows = await cursor.fetchall()
    memories = []
    for row in rows:
        # Get topics
        tcursor = await global_db.execute(
            "SELECT topic_name FROM global_memory_topics WHERE memory_id = ?",
            (row[0],),
        )
        topics = [r[0] for r in await tcursor.fetchall()]

        memories.append({
            "id": row[0],
            "source_project_hash": row[1],
            "source_project_name": row[2] or row[1][:8] + "...",
            "pattern": row[3] or "",
            "confidence": row[4],
            "original_confidence": row[5],
            "depth": row[6],
            "inherited_at": row[7],
            "topics": topics,
        })

    result = {
        "count": len(memories),
        "memories": memories,
    }

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


async def _handle_sync() -> list[TextContent]:
    from soagila.core.inheritance.engine import sync_all_local

    sync_result = await sync_all_local()

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


async def _handle_lineage(arguments: dict) -> list[TextContent]:
    memory_id = arguments.get("memory_id", "")
    if not memory_id:
        return [TextContent(type="text", text=json.dumps({
            "error": "memory_id is required for lineage action.",
        }))]

    from soagila.core.inheritance.engine import get_lineage

    lineage = await get_lineage(memory_id)

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