# -*- coding: utf-8 -*-
"""Dialog views for destructive actions, selection, remote connect, and KV editing."""

from util.runtime import *
from util.utils import node_host_only, _server_id_sort_key
from models.config import Config
from controllers.workers import ClearDatabaseThread, NodeStatusCheckWorker
from views.common import (
    ServerIdTableItem,
    NoWheelComboBox,
    apply_button_style,
    set_button_icon,
)

class ClearDatabaseDialog(QDialog):
    """服务器清档对话框"""
    
    def __init__(self, config: Config, parent=None):
        super().__init__(parent)
        self.config = config
        self.result_info = None
        self.setWindowTitle("服务器清档")
        self.setMinimumSize(500, 400)
        self.init_ui()
    
    def init_ui(self):
        layout = QVBoxLayout(self)
        
        # 警告信息
        warning_label = QLabel("⚠️ 警告：清档将删除游戏数据库和日志数据库，此操作不可恢复！")
        warning_label.setStyleSheet("color: #ff5c6a; font-weight: bold; font-size: 13px;")
        warning_label.setWordWrap(True)
        layout.addWidget(warning_label)
        
        # 服务器选择
        server_group = QGroupBox("选择要清档的服务器")
        server_layout = QVBoxLayout(server_group)
        
        self.server_list = QListWidget()
        self._load_servers()
        server_layout.addWidget(self.server_list)
        
        layout.addWidget(server_group)
        
        # 确认输入
        confirm_layout = QHBoxLayout()
        confirm_layout.addWidget(QLabel("请输入 'DELETE' 确认:"))
        self.confirm_input = QLineEdit()
        self.confirm_input.setPlaceholderText("输入 DELETE")
        confirm_layout.addWidget(self.confirm_input)
        layout.addLayout(confirm_layout)
        
        # 按钮
        button_layout = QHBoxLayout()
        button_layout.addStretch()
        
        cancel_btn = QPushButton("取消")
        cancel_btn.clicked.connect(self.reject)
        apply_button_style(cancel_btn, "neutral")
        button_layout.addWidget(cancel_btn)
        
        self.clear_btn = QPushButton("执行清档")
        apply_button_style(self.clear_btn, "danger")
        self.clear_btn.clicked.connect(self.do_clear)
        button_layout.addWidget(self.clear_btn)
        
        layout.addLayout(button_layout)
    
    def _load_servers(self):
        """加载服务器列表"""
        run_dir = self.config.get('workspace', 'run_dir', default='')
        servers = get_server_list(run_dir)
        
        for category, server_list in servers.items():
            if server_list:
                title_item = QListWidgetItem(f"--- {get_server_type_name(category)} ---")
                title_item.setFlags(Qt.ItemFlag.NoItemFlags)
                self.server_list.addItem(title_item)
                
                for server in sorted(server_list):
                    item = QListWidgetItem(f"  {server}")
                    item.setData(Qt.ItemDataRole.UserRole, server)
                    self.server_list.addItem(item)
    
    def do_clear(self):
        """执行清档"""
        if self.confirm_input.text().strip() != 'DELETE':
            QMessageBox.warning(self, "确认失败", "请输入 'DELETE' 确认清档")
            return
        
        current_item = self.server_list.currentItem()
        if not current_item:
            QMessageBox.warning(self, "未选择", "请先选择要清档的服务器")
            return
        
        server_name = current_item.data(Qt.ItemDataRole.UserRole)
        if not server_name:
            QMessageBox.warning(self, "无效选择", "请选择有效的服务器")
            return
        
        # 二次确认
        reply = QMessageBox.critical(
            self, "最终确认", 
            f"即将清档: {server_name}\n\n"
            "操作步骤:\n"
            "1. 关闭服务器\n"
            "2. 通知中心服和登录服清档\n"
            "3. 删除游戏数据库\n"
            "4. 删除日志数据库\n\n"
            "是否继续？",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
            QMessageBox.StandardButton.No
        )
        
        if reply != QMessageBox.StandardButton.Yes:
            return
        
        self._execute_clear(server_name)
    
    def _execute_clear(self, server_name: str):
        """执行清档 - 使用线程避免阻塞主进程"""
        try:
            import pymysql
        except ImportError:
            try:
                import mysql.connector as pymysql
            except ImportError:
                QMessageBox.critical(self, "错误", "需要安装 pymysql\npip install pymysql")
                return
        
        server_root = self.config.get('workspace', 'server_root', default='')
        run_dir = self.config.get('workspace', 'run_dir', default='')
        kv_config_file = Path(run_dir) / server_name / 'config' / 'kv.config'
        
        if not kv_config_file.exists():
            QMessageBox.critical(self, "错误", f"找不到配置: {kv_config_file}")
            return
        
        # 合并配置（kv.config > user.config > project.config > default.config）
        if server_root:
            merged_cfg = read_merged_config(server_root, server_name, run_dir=run_dir)
        else:
            merged_cfg = read_config_file(str(kv_config_file))
        db_host = merged_cfg.get('db_host', '127.0.0.1')
        db_port = int(merged_cfg.get('db_port', '3306'))
        db_user = merged_cfg.get('db_user', 'root')
        db_pass = merged_cfg.get('db_pass', '')
        db_game = merged_cfg.get('db_game_name', '')
        db_log = merged_cfg.get('db_log_name', '')

        def clean_value(value):
            return str(value or '').strip().strip("'\"")

        server_id = clean_value(merged_cfg.get('server_id', ''))
        center_node = clean_value(merged_cfg.get('center_node', ''))
        login_node = clean_value(merged_cfg.get('login_node', ''))
        
        if not db_game:
            QMessageBox.critical(self, "错误", "无法获取游戏数据库名")
            return
        if not server_id:
            QMessageBox.critical(self, "错误", "无法获取服务器ID")
            return
        try:
            int(server_id)
        except ValueError:
            QMessageBox.critical(self, "错误", f"服务器ID无效: {server_id}")
            return
        if not center_node:
            QMessageBox.critical(self, "错误", "无法获取中心服节点")
            return
        if not login_node:
            QMessageBox.critical(self, "错误", "无法获取登录服节点")
            return
        
        cookie = clean_value(merged_cfg.get('cookie', '')) or clean_value(
            self.config.get('server', 'cookie', default='ddxq2-node')
        ) or 'ddxq2-node'
        erl_path = self.config.get('erlang', 'r25_path', default='') or None
        stop_cmd = build_stop_command(server_name, cookie, erl_path=erl_path)
        
        # 创建并启动清档线程
        self.clear_thread = ClearDatabaseThread(
            server_name=server_name,
            stop_cmd=stop_cmd,
            db_host=db_host,
            db_port=db_port,
            db_user=db_user,
            db_pass=db_pass,
            db_game=db_game,
            db_log=db_log,
            server_id=server_id,
            center_node=center_node,
            login_node=login_node,
            cookie=cookie,
            erl_path=erl_path
        )
        self.clear_thread.finished_signal.connect(self._on_clear_finished)
        self.clear_thread.error_signal.connect(self._on_clear_error)
        self.clear_thread.status_signal.connect(self._on_clear_status)
        
        # 禁用确认按钮，防止重复点击
        self.setEnabled(False)
        self.clear_thread.start()
    
    def _on_clear_status(self, status: str):
        """清档状态更新"""
        self.setWindowTitle(f"服务器清档 - {status}")
    
    def _on_clear_finished(self, deleted: list):
        """清档完成"""
        self.setEnabled(True)
        self.result_info = f"已删除: {', '.join(deleted)}"
        QMessageBox.information(self, "清档完成", f"清档完成\n\n已删除:\n- " + "\n- ".join(deleted))
        self.accept()
    
    def _on_clear_error(self, error: str):
        """清档失败"""
        self.setEnabled(True)
        self.setWindowTitle("服务器清档")
        QMessageBox.critical(self, "清档失败", f"错误: {error}")
