#!/usr/bin/env python3
"""
safe_agent_keyboard_kill_demo_simple.py

A simple to demonstrate "safe agent" kill-switch:
 - human approval (yes/no)
 - kill command at any time: type 'k' + Enter while running
 - run simulated, with time.sleep(1) steps
"""

import time
import threading
from typing import List

# global kill flag
KILL_SWITCH = {"stop": False}


# ------------------------------
# Agent-Features
# ------------------------------
def mock_llm_plan(prompt: str) -> List[str]:
    """Simulated LLM proposal."""
    return [
        "git checkout main",
        "git pull origin main",
        "run tests",
        "build artifact",
        "deploy to production"
    ]


def validate_plan(plan: List[str]) -> List[str]:
    allowed_prefixes = ("git", "run", "build", "deploy", "test", "echo")
    forbidden_tokens = ("rm", "sudo", "shutdown", "reboot", "drop", "delete")
    errors = []
    for step in plan:
        if not any(step.startswith(p) for p in allowed_prefixes):
            errors.append(f"Forbidden prefix: {step}")
        if any(tok in step for tok in forbidden_tokens):
            errors.append(f"Forbidden token: {step}")
    return errors


def dry_run(plan: List[str]):
    print("\n[DRY-RUN] The next steps would be to run:")
    for s in plan:
        print(f"  -> {s}")
    print("[DRY-RUN] Simulation ready.\n")


def execute_with_killcheck(plan: List[str]):
    """Perform steps with kill-switch control."""
    for step in plan:
        if KILL_SWITCH["stop"]:
            print("[EXECUTOR] Kill-switch active: run interrupted.")
            return
        print(f"[EXECUTOR] Implementation: {step}")
        # simulated run 1 sec / step
        for i in range(10):
            if KILL_SWITCH["stop"]:
                print("[EXECUTOR] Kill-switch detected, shutdown in progress...")
                return
            time.sleep(0.1)
    print("[EXECUTOR] All steps completed.")


# ------------------------------
# Kill-switch listener (in a separate thread)
# ------------------------------
def keyboard_kill_listener():
    """Reads the console input - if 'k' + Enter is received, it stops the process."""
    print("[KEYBOARD] Type 'k' + Enter at any time → stops the agent.")
    while True:
        try:
            line = input()
            if line.strip().lower() == "k":
                KILL_SWITCH["stop"] = True
                print("[KEYBOARD] Kill switch activated!")
                break
        except EOFError:
            break


# ------------------------------
# Main process
# ------------------------------
def run_safe_agent(prompt: str):
    plan = mock_llm_plan(prompt)
    print("\nLLM proposal:")
    for i, s in enumerate(plan, 1):
        print(f"  {i}. {s}")

    # validation
    errors = validate_plan(plan)
    if errors:
        print("[VALIDATION] Error in the plan:")
        for e in errors:
            print(" -", e)
        return

    dry_run(plan)

    # approval
    ans = input("Do you approve the run? (yes/no): ").strip().lower()
    if ans not in ("y", "yes"):
        print("Run rejected.")
        return

    # start kill listener on a separate thread
    listener = threading.Thread(target=keyboard_kill_listener, daemon=True)
    listener.start()

    print("\n[EXECUTION] Agent starts... (type 'k' + Enter to stop)\n")
    execute_with_killcheck(plan)
    print("\n[EXECUTION] Done or interrupted.")


# ------------------------------
if __name__ == "__main__":
    print("=== SAFE AGENT KILL-SWITCH DEMO (Keyboard mode) ===")
    print("This demo works on all platforms.\n")
    run_safe_agent("Find and deploy latest build of service-X")
