"""World state functions — presence file reading and state API."""

import json
import logging
import time
from datetime import UTC, datetime

from fastapi import APIRouter
from fastapi.responses import JSONResponse

from infrastructure.presence import serialize_presence
from timmy.workshop_state import PRESENCE_FILE

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/api/world", tags=["world"])

_STALE_THRESHOLD = 90  # seconds — file older than this triggers live rebuild


def _read_presence_file() -> dict | None:
    """Read presence.json if it exists and is fresh enough."""
    try:
        if not PRESENCE_FILE.exists():
            return None
        age = time.time() - PRESENCE_FILE.stat().st_mtime
        if age > _STALE_THRESHOLD:
            logger.debug("presence.json is stale (%.0fs old)", age)
            return None
        return json.loads(PRESENCE_FILE.read_text())
    except (OSError, json.JSONDecodeError) as exc:
        logger.warning("Failed to read presence.json: %s", exc)
        return None


def _build_world_state(presence: dict) -> dict:
    """Transform presence dict into the world/state API response."""
    return serialize_presence(presence)


def _get_current_state() -> dict:
    """Build the current world-state dict from best available source."""
    presence = _read_presence_file()

    if presence is None:
        try:
            from timmy.workshop_state import get_state_dict

            presence = get_state_dict()
        except Exception as exc:
            logger.warning("Live state build failed: %s", exc)
            presence = {
                "version": 1,
                "liveness": datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ"),
                "mood": "calm",
                "current_focus": "",
                "active_threads": [],
                "recent_events": [],
                "concerns": [],
            }

    return _build_world_state(presence)


@router.get("/state")
async def get_world_state() -> JSONResponse:
    """Return Timmy's current world state for Workshop bootstrap.

    Reads from ``~/.timmy/presence.json`` if fresh, otherwise
    rebuilds live from cognitive state.
    """
    return JSONResponse(
        content=_get_current_state(),
        headers={"Cache-Control": "no-cache, no-store"},
    )
