"""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.
"""

import json
import logging
from datetime import datetime, timezone
from pathlib import Path
from typing import Any

from ..utils import state
from ..utils.pe_helpers import CACHE_DIR

logger = logging.getLogger(__name__)

CACHE_META_FILE = "cache-meta.json"
DEFAULT_TTL_HOURS = 24

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"))
    working_dir = state.get_working_dir()

    meta_path = working_dir / CACHE_DIR / CACHE_META_FILE

    if not meta_path.exists():
        return (
            "STATUS: MISSING\n\n"
            "No reference data cache found.\n"
            "Call load_compass_data to initialize."
        )

    try:
        meta = json.loads(meta_path.read_text())
    except (json.JSONDecodeError, OSError) as exc:
        logger.warning("Could not read cache meta: %s", exc)
        return (
            "STATUS: MISSING\n\n"
            "Cache meta file exists but could not be read.\n"
            "Call load_compass_data to reinitialize."
        )

    cached_at_str = meta.get("cached_at")
    if not cached_at_str:
        return (
            "STATUS: MISSING\n\n"
            "Cache meta file is missing the cached_at timestamp.\n"
            "Call load_compass_data to reinitialize."
        )

    try:
        cached_at = datetime.fromisoformat(cached_at_str)
    except (ValueError, TypeError):
        return (
            "STATUS: MISSING\n\n"
            "Cache meta file has an invalid cached_at timestamp.\n"
            "Call load_compass_data to reinitialize."
        )

    ttl_hours = meta.get("ttl_hours", DEFAULT_TTL_HOURS)
    now = datetime.now(timezone.utc)
    age_hours = (now - cached_at).total_seconds() / 3600
    org_alias = meta.get("org_alias", "unknown")

    if age_hours > ttl_hours:
        return (
            f"STATUS: STALE\n\n"
            f"Cache age: {age_hours:.1f} hours (TTL: {ttl_hours} hours)\n"
            f"Cached at: {cached_at_str}\n"
            f"Org: {org_alias}\n\n"
            f"Call load_compass_data to refresh."
        )

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