"""
InteractiveInputHandler - 交互输入处理
"""

import asyncio
from typing import Any

from app.agents.tools.terminal_engine import PTYManager


class InteractiveInputHandler:
    """交互输入处理器"""

    def __init__(self, pty_manager: PTYManager):
        self.pty_manager = pty_manager
        self._pending_inputs: dict[str, asyncio.Event] = {}
        self._input_cache: dict[str, str] = {}

    async def wait_for_input(self, session_id: str, prompt: str) -> str:
        """等待用户输入（如 "y" 确认）"""
        event = asyncio.Event()
        self._pending_inputs[session_id] = event

        # 发送提示
        from app.routers.terminal import manager

        try:
            await manager.send(session_id, f"\n{prompt}\n")
        except Exception:
            pass

        # 等待输入完成
        try:
            await asyncio.wait_for(event.wait(), timeout=60.0)
        except asyncio.TimeoutError:
            del self._pending_inputs[session_id]
            return self._input_cache.get(session_id, "")

        del self._pending_inputs[session_id]

        return self._input_cache.get(session_id, "")

    async def send_input(self, session_id: str, data: str):
        """用户发送输入"""
        self._input_cache[session_id] = data
        if session_id in self._pending_inputs:
            self._pending_inputs[session_id].set()

        # 同时写入 PTY
        await self.pty_manager.write(session_id, data + "\n")

    def clear_input(self, session_id: str):
        """清除输入缓存"""
        if session_id in self._input_cache:
            del self._input_cache[session_id]
        if session_id in self._pending_inputs:
            self._pending_inputs[session_id].set()  # 取消等待
            del self._pending_inputs[session_id]
