"""
用户交互处理器
处理需要用户输入并发送响应给服务端的事件
"""

from typing import Dict, Any


class InteractionHandler:
    """用户交互处理器 - 处理需要用户交互的事件"""

    def __init__(self, ws_client, tui, renderer, app_state):
        """
        Args:
            ws_client: WebSocket 客户端
            tui: TUI 实例
            renderer: 流式渲染器
            app_state: 应用状态
        """
        self.ws_client = ws_client
        self.tui = tui
        self.renderer = renderer
        self.app_state = app_state

    async def handle_permission_request(self, event: Dict[str, Any]):
        """处理权限请求事件"""
        from core.logger import log_event

        log_event("cli_permission_request_received", event=event)

        data = event.get("data", {})
        request_id = data.get("request_id")
        permission = data.get("permission")
        pattern = data.get("pattern")
        metadata = data.get("metadata", {})

        # 暂停渲染以进行交互
        self.renderer.pause_for_interaction()

        # 使用异步版本的权限询问
        choice = await self.tui.ask_permission_async(
            permission,
            pattern,
            "",  # description
            metadata.get("args")
        )

        log_event("user_choice_received", choice=choice)

        # 解析用户选择
        approved = choice in ["y", "a"]
        remember = choice in ["a", "d"]
        remember_pattern = pattern if remember else None

        # 发送权限响应到服务器
        await self.ws_client.send_permission_response(
            request_id=request_id,
            approved=approved,
            remember=remember,
            remember_pattern=remember_pattern
        )

        log_event("permission_response_sent")

        # 恢复渲染
        self.renderer.resume_after_interaction()

    async def handle_interaction_request(self, event: Dict[str, Any]):
        """处理统一交互请求事件"""
        from core.logger import log_event
        from rich.text import Text

        log_event("cli_interaction_request_received", event=event)

        data = event.get("data", {})
        request_id = data.get("request_id")
        interaction_type = data.get("interaction_type")
        title = data.get("title", "")
        message = data.get("message", "")
        options = data.get("options", [])
        metadata = data.get("metadata", {})
        default_value = data.get("default_value")

        # 暂停渲染以进行交互
        self.renderer.pause_for_interaction()

        # 根据交互类型处理
        approved = False
        value = default_value
        remember = False
        remember_scope = "session"

        if interaction_type == "permission":
            # 权限请求
            permission = metadata.get("permission", "unknown")
            pattern = metadata.get("pattern", "")

            choice = await self.tui.ask_permission_async(
                permission,
                pattern,
                message,
                metadata.get("args")
            )

            approved = choice in ["y", "a"]
            remember = choice in ["a", "d"]
            if choice == "a":
                remember_scope = "pattern"
            elif choice == "d":
                remember_scope = "session"
            value = choice

        elif interaction_type == "confirmation":
            # 确认请求
            self.tui._write_safe(Text(""))
            title_text = Text()
            title_text.append("⚠️  ", style="bold yellow")
            title_text.append(title)
            self.tui._write_safe(title_text)
            self.tui._write_safe(Text(f"   {message}"))
            self.tui._write_safe(Text(""))

            for i, opt in enumerate(options):
                label = opt.get("label", opt.get("value", f"选项{i+1}"))
                self.tui._write_safe(Text(f"   [{i+1}] {label}"))

            try:
                user_input = await self.tui.get_user_input_async()
                if user_input == "1":
                    approved = True
                    value = options[0].get("value") if options else "confirm"
                else:
                    approved = False
                    value = options[1].get("value") if len(options) > 1 else "cancel"
            except (EOFError, KeyboardInterrupt):
                approved = False
                value = "cancel"

        elif interaction_type == "input":
            # 输入请求
            self.tui._write_safe(Text(""))
            title_text = Text()
            title_text.append("📝 ", style="bold cyan")
            title_text.append(title)
            self.tui._write_safe(title_text)
            self.tui._write_safe(Text(f"   {message}"))

            try:
                user_input = await self.tui.get_user_input_async()
                if user_input:
                    approved = True
                    value = user_input
                else:
                    approved = False
                    value = default_value
            except (EOFError, KeyboardInterrupt):
                approved = False
                value = default_value

        elif interaction_type == "choice":
            # 选择请求
            self.tui._write_safe(Text(""))
            title_text = Text()
            title_text.append("🔘 ", style="bold cyan")
            title_text.append(title)
            self.tui._write_safe(title_text)
            self.tui._write_safe(Text(f"   {message}"))
            self.tui._write_safe(Text(""))

            for i, opt in enumerate(options):
                label = opt.get("label", opt.get("value", f"选项{i+1}"))
                desc = opt.get("description", "")
                if desc:
                    self.tui._write_safe(Text(f"   [{i+1}] {label} - {desc}"))
                else:
                    self.tui._write_safe(Text(f"   [{i+1}] {label}"))

            try:
                user_input = await self.tui.get_user_input_async()
                idx = int(user_input) - 1
                if 0 <= idx < len(options):
                    approved = True
                    value = options[idx].get("value")
                else:
                    approved = False
                    value = default_value
            except (ValueError, EOFError, KeyboardInterrupt):
                approved = False
                value = default_value

        elif interaction_type == "clarify":
            # 用户澄清请求
            allow_text_input = metadata.get("allow_text_input", True)

            # 调用 TUI 的 ask_clarify_async（内部会在功能区显示选项）
            value = await self.tui.ask_clarify_async(message, options, allow_text_input)

            if value:
                approved = True
            else:
                approved = False
                value = default_value

        else:
            # 未知类型，默认拒绝
            log_event("unknown_interaction_type", interaction_type=interaction_type)
            approved = False
            value = default_value

        # 发送交互响应到服务器
        await self.ws_client.send_interaction_response(
            request_id=request_id,
            approved=approved,
            value=value,
            remember=remember,
            remember_scope=remember_scope
        )

        log_event("interaction_response_sent")

        # 恢复渲染
        self.renderer.resume_after_interaction()

    async def handle_disconnect(self, reason: str):
        """处理 WebSocket 断开连接"""
        import os
        import sys
        from core.logger import log_event

        log_event("ws_disconnect_callback", reason=reason)
        self.renderer.on_error(reason)
        self.tui.print_error(f"连接断开: {reason}")
        log_event("connection_lost", reason=reason)
        self.app_state.set_input_state()
        print(f"\n✗ Error: 连接已断开: {reason}", file=sys.stderr, flush=True)
        print("请检查服务端状态或重新启动", file=sys.stderr, flush=True)
        os._exit(1)

    async def handle_ws_error(self, error: str):
        """处理 WebSocket 错误"""
        import os
        import sys
        from core.logger import log_event

        log_event("ws_error_callback", error=error)
        self.renderer.on_error(f"连接错误: {error}")
        log_event("ws_error", error=error)
        print(f"\n✗ Error: WebSocket 错误: {error}", file=sys.stderr, flush=True)
        os._exit(1)
