#!/usr/bin/env python3
"""Fake pepper-ctl that serves recorded responses for eval replay mode.

Drop-in replacement for pepper-ctl: reads from a recording.jsonl fixture
and returns the next matching response for the given command.

Usage:
    PEPPER_REPLAY_FIXTURE=path/to/recording.jsonl pepper-ctl-replay look
    PEPPER_REPLAY_FIXTURE=path/to/recording.jsonl pepper-ctl-replay defaults --action list
"""

import json
import os
import sys
from pathlib import Path


def main():
    fixture_path = os.environ.get("PEPPER_REPLAY_FIXTURE")
    if not fixture_path:
        print("Error: PEPPER_REPLAY_FIXTURE not set", file=sys.stderr)
        sys.exit(1)

    state_file = Path(fixture_path + ".state")
    cursor = int(state_file.read_text().strip()) if state_file.exists() else 0

    recordings = []
    for line in Path(fixture_path).read_text().splitlines():
        line = line.strip()
        if line:
            try:
                recordings.append(json.loads(line))
            except json.JSONDecodeError:
                continue

    if not sys.argv[1:]:
        print("Usage: pepper-ctl-replay <command> [args...]", file=sys.stderr)
        sys.exit(1)

    command = sys.argv[1]
    tool_name = f"mcp__pepper__{command}"

    # Match: sequential first, then by tool name
    matched = None
    if cursor < len(recordings) and recordings[cursor]["tool"] == tool_name:
        matched = recordings[cursor]
        cursor += 1
    else:
        for i in range(cursor, len(recordings)):
            if recordings[i]["tool"] == tool_name:
                matched = recordings[i]
                cursor = i + 1
                break

    state_file.write_text(str(cursor))

    if matched:
        print(matched["response"])
        sys.exit(1 if matched.get("is_error", False) else 0)
    else:
        print(json.dumps({"status": "error", "error": f"[REPLAY] No recorded response for {command}"}))
        sys.exit(1)


if __name__ == "__main__":
    main()
