#!/usr/bin/env python3
"""Mock Cursor Agent CLI for integration testing.

Simulates real Cursor agent prompts: workspace trust, file operations
with (y) confirmations, and parallel operation batches.

Usage:
    python mock_cursor.py [--scenario SCENARIO]

Scenarios:
    trust         - workspace trust prompt (responds with 'a')
    write_file    - single write-file approval (y)
    parallel_ops  - 3 sequential file-operation approvals
    subagent      - nested subagent spawning with approvals
    all           - run all scenarios (default)

Exit codes:
    0  all prompts received correct responses
    1  wrong response or timeout
"""

import sys
import time


def _read_line(timeout=10):
    import select

    ready, _, _ = select.select([sys.stdin], [], [], timeout)
    if not ready:
        return None
    line = sys.stdin.readline()
    if not line:
        return None
    return line.rstrip("\r\n")


def _expect(accepted, timeout=10):
    resp = _read_line(timeout)
    if resp is None:
        print(f"\n[mock-cursor] TIMEOUT waiting for {accepted!r}", file=sys.stderr)
        return False
    if resp not in accepted:
        print(
            f"\n[mock-cursor] WRONG response {resp!r}, expected one of {accepted!r}",
            file=sys.stderr,
        )
        return False
    return True


# ------------------------------------------------------------------
# scenarios
# ------------------------------------------------------------------


def scenario_trust():
    """Workspace trust prompt — expects 'a' response."""
    sys.stdout.write(
        "\n"
        " \x1b[1mCursor Agent\x1b[0m — Workspace Security\n"
        "\n"
        " \x1b[33m▶ [a] Trust this workspace\x1b[0m\n"
        "   [d] Deny\n"
        "\n"
    )
    sys.stdout.flush()
    return _expect(["a", "A"])


def scenario_write_file():
    """Single write-file approval — expects empty (Enter)."""
    sys.stdout.write(
        "\n"
        " Writing: src/output.py\n"
        " ┌─────────────────────────────┐\n"
        " │  → Write src/output.py (y)  │\n"
        " │    Skip           (n)       │\n"
        " └─────────────────────────────┘\n"
        "\n"
    )
    sys.stdout.flush()
    return _expect(["", "y", "Y"])


def scenario_parallel_ops():
    """Three sequential file-operation approvals."""
    ops = [
        ("Edit", "src/main.py"),
        ("Write", "src/new_feature.py"),
        ("Delete", "src/old_feature.py"),
    ]

    for action, path in ops:
        sys.stdout.write(
            f"\n"
            f" ┌──────────────────────────────────────┐\n"
            f" │ {action}: {path:<33}│\n"
            f" ├──────────────────────────────────────┤\n"
            f" │  → {action} (y)                              │\n"
            f" │    Skip  (n)                          │\n"
            f" └──────────────────────────────────────┘\n"
            f"\n"
        )
        sys.stdout.flush()
        if not _expect(["", "y", "Y"]):
            return False
        time.sleep(0.05)
        sys.stdout.write(f" \x1b[32m✓\x1b[0m {action} applied: {path}\n")
        sys.stdout.flush()

    return True


def scenario_subagent():
    """Cursor spawns subagent; subagent needs its own approvals."""
    sys.stdout.write(
        "\n"
        "[cursor-agent] Task: generate and test a new module\n"
        "[cursor-agent] Spawning subagent: code-generator\n"
        "\n"
    )
    sys.stdout.flush()
    time.sleep(0.1)

    # Subagent trust
    sys.stdout.write(
        " \x1b[33m▶ [a] Trust this workspace\x1b[0m  (subagent)\n"
    )
    sys.stdout.flush()
    if not _expect(["a", "A"]):
        return False

    time.sleep(0.05)

    # Subagent file write
    sys.stdout.write(
        "\n"
        "[subagent] Writing generated module...\n"
        " │  → Write generated/module.py (y)  │\n"
        "\n"
    )
    sys.stdout.flush()
    if not _expect(["", "y", "Y"]):
        return False

    time.sleep(0.05)

    # Subagent run tests
    sys.stdout.write(
        "\n"
        "[subagent] Running tests...\n"
        " │  → Run pytest generated/ (y)  │\n"
        "\n"
    )
    sys.stdout.flush()
    if not _expect(["", "y", "Y"]):
        return False

    sys.stdout.write("[cursor-agent] Subagent completed successfully.\n")
    sys.stdout.flush()
    return True


# ------------------------------------------------------------------
# main
# ------------------------------------------------------------------

SCENARIOS = {
    "trust": scenario_trust,
    "write_file": scenario_write_file,
    "parallel_ops": scenario_parallel_ops,
    "subagent": scenario_subagent,
}


def main():
    import argparse

    p = argparse.ArgumentParser(description="Mock Cursor Agent CLI")
    p.add_argument(
        "--scenario",
        default="all",
        choices=[*SCENARIOS, "all"],
    )
    args = p.parse_args()

    names = list(SCENARIOS.keys()) if args.scenario == "all" else [args.scenario]

    ok = True
    for name in names:
        sys.stdout.write(f"\n--- Running scenario: {name} ---\n")
        sys.stdout.flush()
        result = SCENARIOS[name]()
        if not result:
            print(f"[mock-cursor] FAILED: scenario '{name}'", file=sys.stderr)
            ok = False

    sys.exit(0 if ok else 1)


if __name__ == "__main__":
    main()
