#!/usr/bin/env python3
"""
Run a single agent turn headlessly (no UI, no app).

Useful for fast iteration when debugging the agent loop or tools. Runs
run_raw_agent with a minimal prompt and prints the result.

Usage:
  python scripts/run_single_turn.py "What is 2+2?"
  python scripts/run_single_turn.py "List files in the workspace" --thread test_turn_1

Set MUGI_TRACE=1 or trace_conversations = true in mugi_config.toml to
generate a trace for replay_trace.py.
"""
from __future__ import annotations

import os
import sys
import uuid

# Ensure project root on path
_SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
_PROJECT_ROOT = os.path.dirname(_SCRIPT_DIR)
if _PROJECT_ROOT not in sys.path:
    sys.path.insert(0, _PROJECT_ROOT)


def main() -> None:
    if len(sys.argv) < 2:
        print(__doc__)
        print("\nUsage: python scripts/run_single_turn.py \"<prompt>\" [--thread <thread_id>]")
        sys.exit(1)

    prompt = sys.argv[1]
    thread_id = "single_turn_" + uuid.uuid4().hex[:8]
    if "--thread" in sys.argv:
        idx = sys.argv.index("--thread")
        if idx + 1 < len(sys.argv):
            thread_id = sys.argv[idx + 1]

    messages = [{"role": "user", "content": prompt}]

    from agent_loop import run_raw_agent

    collector = []

    def on_chunk(text):
        if text:
            collector.append(text)
            print(text, end="", flush=True)

    def on_finished(text):
        if text and not collector:
            collector.append(text)
        print()  # newline after stream

    def on_log(level, msg):
        print(f"[{level}] {msg}", file=sys.stderr)

    def on_error(err):
        print(f"[ERROR] {err}", file=sys.stderr)

    print(f"Thread: {thread_id}")
    print(f"Prompt: {prompt[:80]}{'...' if len(prompt) > 80 else ''}")
    print("-" * 40)

    result = run_raw_agent(
        messages=messages,
        thread_id=thread_id,
        config=None,
        on_chunk=on_chunk,
        on_log=on_log,
        on_error=on_error,
        on_finished=on_finished,
        research_mode=False,
        has_media_attachment=False,
        include_cli=False,
        policy_context=None,  # loads from live prefs inside run_raw_agent
    )

    print("-" * 40)
    full = "".join(collector) if collector else (result or "")
    if full:
        print(f"Result ({len(full)} chars)")
    else:
        print("No output.")


if __name__ == "__main__":
    main()
