"""check_compass_data -- Ultra-fast cache validity check.

No SOQL queries. Reads .cache/cache-meta.json and compares the
timestamp against a 24-hour TTL. The AI calls this at the start
of every session to decide whether load_compass_data is needed.
"""

from typing import Any

from ..utils import state, pe_helpers

TOOL_DEFINITION = {
    "name": "check_compass_data",
    "description": (
        "Check if the local reference data cache is fresh. "
        "Call this at the start of every session. If STALE or MISSING, "
        "call load_compass_data to refresh. No org queries are made."
    ),
    "inputSchema": {
        "type": "object",
        "properties": {
            "working_directory": {
                "type": "string",
                "description": "Workspace directory. The AI passes this automatically.",
            },
        },
        "required": [],
    },
}


async def run(arguments: dict[str, Any]) -> str:
    """Execute the check_compass_data tool."""
    state.set_working_dir(arguments.get("working_directory"))
    result = pe_helpers.validate_and_load_cache(state.get_working_dir())
    status = result["status"]

    if status == "MISSING":
        return (
            f"STATUS: MISSING\n\n"
            f"{result['reason']}\n"
            f"Call load_compass_data to initialize."
        )

    if status == "STALE":
        return (
            f"STATUS: STALE\n\n"
            f"Cache age: {result['age_hours']:.1f} hours (TTL: {result['ttl_hours']} hours)\n"
            f"Cached at: {result['cached_at']}\n"
            f"Org: {result['org_alias']}\n\n"
            f"Call load_compass_data to refresh."
        )

    return (
        f"STATUS: VALID\n\n"
        f"Cache age: {result['age_hours']:.1f} hours (TTL: {result['ttl_hours']} hours)\n"
        f"Cached at: {result['cached_at']}\n"
        f"Org: {result['org_alias']}\n\n"
        f"Reference data is fresh. Proceed with your request."
    )
