"""Phase 1 — Gather: accept raw input, produce structured context.

This is the sensory phase. It receives a raw ContextPayload and enriches
it with whatever context Timmy needs before reasoning. In the stub form,
it simply passes the payload through with a phase marker.
"""

from __future__ import annotations

import logging

from loop.schema import ContextPayload

logger = logging.getLogger(__name__)


def gather(payload: ContextPayload) -> ContextPayload:
    """Accept raw input and return structured context for reasoning.

    When the payload carries a ``perception`` dict in metadata (injected by
    the heartbeat loop from a WorldInterface adapter), that observation is
    folded into the gathered context.  Otherwise behaves as before.
    """
    logger.info(
        "Phase 1 (Gather) received: source=%s content_len=%d tokens=%d",
        payload.source,
        len(payload.content),
        payload.token_count,
    )

    extra: dict = {"phase": "gather", "gathered": True}

    # Enrich with world observation when present
    perception = payload.metadata.get("perception")
    if perception:
        extra["world_observation"] = perception
        logger.info(
            "Phase 1 (Gather) world observation: location=%s entities=%d events=%d",
            perception.get("location", "?"),
            len(perception.get("entities", [])),
            len(perception.get("events", [])),
        )

    result = payload.with_metadata(**extra)

    logger.info(
        "Phase 1 (Gather) produced: metadata_keys=%s",
        sorted(result.metadata.keys()),
    )
    return result
