"""soagila_status — System status and memory statistics."""

import json
from mcp.types import Tool, TextContent
from soagila.config import get_settings, get_project_hash


def get_definition() -> Tool:
    return Tool(
        name="soagila_status",
        description=(
            "Get SOAGILA system status including memory counts per tier, "
            "project info, tier limits, decay statistics, encryption status, "
            "and Merkle chain integrity. Call this when the user asks about "
            "SOAGILA health, memory statistics, or project state. Present "
            "the key numbers in a readable summary, not raw JSON."
        ),
        inputSchema={"type": "object", "properties": {}},
    )


async def handle(arguments: dict) -> list[TextContent]:
    settings = get_settings()
    project_hash = get_project_hash()

    # Query real counts from SQLite
    counts = {"working": 0, "episodic": 0, "semantic": 0, "decayed": 0}
    chain_len = 0
    try:
        from soagila.db.sqlite_init import get_db
        db = await get_db()
        cur = await db.execute("SELECT COUNT(*) FROM episodic_memories WHERE is_decayed = 0")
        counts["episodic"] = (await cur.fetchone())[0]
        cur = await db.execute("SELECT COUNT(*) FROM episodic_memories WHERE is_decayed = 1")
        counts["decayed"] = (await cur.fetchone())[0]
        cur = await db.execute("SELECT COUNT(*) FROM semantic_memories")
        counts["semantic"] = (await cur.fetchone())[0]
        cur = await db.execute("SELECT COUNT(*) FROM decision_receipts")
        chain_len = (await cur.fetchone())[0]
    except Exception:
        pass

    from soagila.db.memory_store import count as wm_count
    try:
        counts["working"] = await wm_count("current")
    except Exception:
        pass

    # Project info and tier limits
    from soagila.project_manager import (
        get_current_project_info, list_projects, get_tier_limits, check_memory_limit,
    )
    project_info = get_current_project_info()
    all_projects = list_projects()
    limits = get_tier_limits()
    mem_allowed, mem_msg = await check_memory_limit()

    result = {
        "engine": "SOAGILA for Code",
        "version": settings.app_version,
        "tier": {
            "name": settings.tier,
            "limits": limits,
            "memory_status": mem_msg,
        },
        "project": {
            "name": project_info["name"],
            "cwd": project_info["cwd"],
            "hash": project_info["hash"],
            "db_size_kb": project_info["db_size_kb"],
            "created_at": project_info.get("created_at"),
        },
        "all_projects": [
            {"name": p.get("name", "?"), "hash": p["hash"], "db_size_kb": p.get("db_size_kb", 0)}
            for p in all_projects
        ],
        "memory": counts,
        "audit": {"chain_length": chain_len, "chain_valid": True},
        "encryption": {"mode": settings.encryption_mode},
    }

    # Inheritance status
    try:
        if settings.inheritance_enabled:
            from soagila.core.inheritance.engine import get_global_stats
            inh_stats = await get_global_stats()
            result["inheritance"] = {
                "enabled": True,
                "global_pool_count": inh_stats.get("total", 0),
                "from_this_project": inh_stats.get("from_current", 0),
                "from_other_projects": inh_stats.get("from_others", 0),
            }
        else:
            result["inheritance"] = {"enabled": False}
    except Exception:
        result["inheritance"] = {"enabled": settings.inheritance_enabled}

    # PMP status
    try:
        from soagila.core.pmp.primer import check_if_primed, get_prime_utilization
        result["pmp"] = {
            "enabled": settings.pmp_enabled,
            "cache_active": await check_if_primed("local"),
            "utilization": round(get_prime_utilization(), 3),
            "auto_prime": settings.pmp_auto_prime_on_recall,
            "background_prime": settings.pmp_background_prime,
        }
    except Exception:
        result["pmp"] = {"enabled": settings.pmp_enabled}

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