"""soagila_prime — Predictive Memory Priming with pattern analysis and prediction."""

import json
from mcp.types import Tool, TextContent


def get_definition() -> Tool:
    return Tool(
        name="soagila_prime",
        description=(
            "Predictive Memory Priming (PMP) — proactively loads relevant memories "
            "into the fast-access cache for faster recall. Actions: "
            "'prime' (default) pre-loads memories, "
            "'status' shows cache and hit rates, "
            "'patterns' shows detected usage patterns, "
            "'predict' shows predicted next topics. "
            "Use at session start or when switching tasks."
        ),
        inputSchema={
            "type": "object",
            "properties": {
                "action": {
                    "type": "string",
                    "enum": ["prime", "status", "patterns", "predict"],
                    "description": (
                        "'prime' — pre-load memories (default). "
                        "'status' — cache info, hit rates, utilization. "
                        "'patterns' — detected usage patterns. "
                        "'predict' — predicted next topics."
                    ),
                },
                "context_hint": {
                    "type": "string",
                    "description": "Context hint to focus priming (e.g., 'working on auth module').",
                },
            },
        },
    )


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

    if action == "prime":
        return await _handle_prime(arguments)
    elif action == "status":
        return await _handle_status()
    elif action == "patterns":
        return await _handle_patterns()
    elif action == "predict":
        return await _handle_predict()
    else:
        return [TextContent(type="text", text=json.dumps({
            "error": f"Unknown action: {action}. Use 'prime', 'status', 'patterns', or 'predict'.",
        }))]


async def _handle_prime(arguments: dict) -> list[TextContent]:
    """Pre-load memories into cache."""
    context_hint = arguments.get("context_hint")

    from soagila.core.pmp.primer import prime_for_user, prime_for_context

    if context_hint:
        priming = await prime_for_context("local", context_hint)
    else:
        priming = await prime_for_user("local", trigger="manual")

    result = {
        "primed": priming.primed,
        "episodic_count": priming.episodic_count,
        "semantic_count": priming.semantic_count,
        "total_primed": priming.total_primed,
        "from_cache": priming.from_cache,
        "trigger": priming.trigger,
        "context_hint": context_hint,
    }

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


async def _handle_status() -> list[TextContent]:
    """Show PMP cache status, hit rates, utilization."""
    from soagila.config import get_settings
    from soagila.core.pmp.primer import check_if_primed, get_prime_utilization
    from soagila.core.ima.self_learning import get_metrics

    settings = get_settings()
    ima = get_metrics()
    ima_dict = ima.to_dict()
    pmp_stats = ima_dict.get("pmp", {})

    result = {
        "enabled": settings.pmp_enabled,
        "cache_active": await check_if_primed("local"),
        "cache_ttl_seconds": settings.pmp_cache_ttl,
        "auto_prime_on_recall": settings.pmp_auto_prime_on_recall,
        "background_prime": settings.pmp_background_prime,
        "cache_hits": pmp_stats.get("cache_hits", 0),
        "cache_misses": pmp_stats.get("cache_misses", 0),
        "hit_rate": pmp_stats.get("hit_rate", 0.0),
        "utilization": round(get_prime_utilization(), 3),
        "relevance_threshold": settings.pmp_relevance_threshold,
        "prediction_depth": settings.pmp_prediction_depth,
    }

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


async def _handle_patterns() -> list[TextContent]:
    """Show detected usage patterns."""
    from soagila.core.pmp.pattern_detector import detect_usage_patterns
    patterns = await detect_usage_patterns("local")
    return [TextContent(type="text", text=json.dumps(patterns, indent=2))]


async def _handle_predict() -> list[TextContent]:
    """Show predicted next topics."""
    from soagila.config import get_settings
    from soagila.core.pmp.predictor import predict_topics, get_prediction_metrics

    settings = get_settings()
    predictions = await predict_topics(
        "local",
        max_predictions=settings.pmp_prediction_depth,
    )

    result = {
        "predictions": [p.to_dict() for p in predictions],
        "count": len(predictions),
        "metrics": get_prediction_metrics(),
    }

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