"""Loop runner — orchestrates the three phases in sequence.

Runs Gather → Reason → Act as a single cycle, passing output from each
phase as input to the next. The Act output feeds back as input to the
next Gather call.
"""

from __future__ import annotations

import logging

from loop.phase1_gather import gather
from loop.phase2_reason import reason
from loop.phase3_act import act
from loop.schema import ContextPayload

logger = logging.getLogger(__name__)


def run_cycle(payload: ContextPayload) -> ContextPayload:
    """Execute one full Gather → Reason → Act cycle.

    Returns the Act phase output, which can be fed back as input
    to the next cycle.
    """
    logger.info("=== Loop cycle start: source=%s ===", payload.source)

    gathered = gather(payload)
    reasoned = reason(gathered)
    acted = act(reasoned)

    logger.info(
        "=== Loop cycle complete: phases=%s ===",
        [
            gathered.metadata.get("phase"),
            reasoned.metadata.get("phase"),
            acted.metadata.get("phase"),
        ],
    )
    return acted
