#!/usr/bin/env python3
"""
Replay a conversation trace without calling the LLM.

Loads a trace file from ~/.mugi/logs/traces/<thread_id>.jsonl and re-executes
each tool_call in order. Use this to debug tool behavior or verify tool logic
without waiting for the agent/LLM.

Usage:
  python scripts/replay_trace.py <thread_id>           # replay latest trace for thread
  python scripts/replay_trace.py <path/to/trace.jsonl> # replay from file path

Requires trace_conversations = true in [debug] (mugi_config.toml) to have
generated the trace.

For parity with the current app, run with the backend venv, e.g.
``~/.mugi/venv/bin/python scripts/replay_trace.py ...`` from the repo root.
"""
from __future__ import annotations

import os
import sys

# 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)

from mugi_testing.trace_replay import find_trace_path, load_trace_entries, replay_tool_calls


def main() -> None:
    if len(sys.argv) < 2:
        print(__doc__)
        print("\nUsage: python scripts/replay_trace.py <thread_id|trace_path> [--dry-run]")
        sys.exit(1)

    arg = sys.argv[1]
    dry_run = "--dry-run" in sys.argv

    path = find_trace_path(arg)
    if not path:
        print(f"Trace not found for: {arg}")
        sys.exit(1)

    print(f"Loading trace: {path}")
    entries = load_trace_entries(path)
    if not entries:
        print("Trace is empty.")
        sys.exit(1)

    print(f"Loaded {len(entries)} trace entries")
    events = {e.get("event") for e in entries}
    print(f"Event types: {events}")

    results = replay_tool_calls(entries, dry_run=dry_run)
    if not results:
        print("No tool_call events in trace.")
    else:
        print(f"Replaying {len(results)} tool call(s)...")
        for i, r in enumerate(results):
            print(f"\n--- Tool {i + 1}/{len(results)}: {r.tool_name} (round {r.round}) ---")
            if r.phase == "dry_run":
                print(f"  [dry run] args: {r.message[:200]}...")
            elif r.phase == "unknown_tool":
                print(f"  ERROR: {r.message}")
            elif r.phase == "invoke_ok":
                print(f"  OK ({len(r.message)} chars preview)")
                print(f"  Result: {r.message}")
            else:
                print(f"  ERROR ({r.exception_type}): {r.message}")

    print("\nDone.")


if __name__ == "__main__":
    main()
