# -*- coding: utf-8 -*-
"""Console widgets used by multiple views."""

from util.runtime import *

class ConsoleWindow(QDialog):
    """独立的控制台窗口"""

    MAX_BLOCKS = 4000

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("输出控制台")
        self.setMinimumSize(800, 600)
        self.setModal(False)

        layout = QVBoxLayout(self)
        layout.setContentsMargins(10, 10, 10, 10)

        self.console_text = QTextEdit()
        self.console_text.setReadOnly(True)
        self.console_text.setFont(QFont("Consolas", 11))
        self.console_text.setStyleSheet("""
            QTextEdit {
                background-color: #242932;
                color: #e7edf6;
                border: 1px solid #3a4352;
                border-radius: 8px;
                padding: 12px;
            }
        """)
        self.console_text.document().setMaximumBlockCount(self.MAX_BLOCKS)
        layout.addWidget(self.console_text)

        btn_layout = QHBoxLayout()
        btn_layout.addStretch()

        clear_btn = QPushButton("清空")
        clear_btn.clicked.connect(self.console_text.clear)
        btn_layout.addWidget(clear_btn)

        close_btn = QPushButton("关闭")
        close_btn.clicked.connect(self.close)
        btn_layout.addWidget(close_btn)

        layout.addLayout(btn_layout)

    def append_output(self, text):
        """追加输出（QTextCharFormat 着色，不用 insertHtml）"""
        cursor = self.console_text.textCursor()
        cursor.movePosition(cursor.MoveOperation.End)
        self.console_text.setTextCursor(cursor)

        from PyQt6.QtGui import QTextCharFormat
        for line in text.split('\n'):
            if not line and text.endswith('\n'):
                continue
            fmt = QTextCharFormat()
            tl = line.lower()
            if '[错误]' in line or 'error' in tl:
                fmt.setForeground(QColor("#ff5c6a"))
            elif '[警告]' in line or 'warning' in tl:
                fmt.setForeground(QColor("#f5b04b"))
            elif '执行命令' in line or '命令执行完成' in line:
                fmt.setForeground(QColor("#2dd4bf"))
            elif '成功' in line or 'success' in tl:
                fmt.setForeground(QColor("#25c889"))
            else:
                fmt.setForeground(QColor("#e7edf6"))
            cursor.insertText(line + '\n', fmt)

        self.console_text.ensureCursorVisible()

    def sync_content(self, plain_text: str):
        """同步主控制台的纯文本内容"""
        self.console_text.setPlainText(plain_text)
        self.console_text.moveCursor(self.console_text.textCursor().MoveOperation.End)


class OutputConsole(QTextEdit):
    """输出控制台——使用 QTextCharFormat 着色 + 文档限幅，避免卡顿"""

    MAX_BLOCKS = 4000  # 最多保留行数

    def __init__(self):
        super().__init__()
        self.setReadOnly(True)
        self.setFont(QFont("Consolas", 10))
        self.setStyleSheet("""
            QTextEdit {
                background-color: #242932;
                color: #e7edf6;
                border: 1px solid #3a4352;
                border-radius: 8px;
                padding: 8px;
            }
        """)
        self.document().setMaximumBlockCount(self.MAX_BLOCKS)
        self.console_window = None

        self._fmt_time = self._make_fmt("#4f8cff")
        self._fmt_error = self._make_fmt("#ff5c6a")
        self._fmt_warn = self._make_fmt("#f5b04b")
        self._fmt_cmd = self._make_fmt("#2dd4bf")
        self._fmt_ok = self._make_fmt("#25c889")
        self._fmt_default = self._make_fmt("#e7edf6")

    @staticmethod
    def _make_fmt(color_hex: str):
        from PyQt6.QtGui import QTextCharFormat
        fmt = QTextCharFormat()
        fmt.setForeground(QColor(color_hex))
        return fmt

    def _pick_fmt(self, text: str):
        tl = text.lower()
        if text.startswith('[') and ']' in text[:12]:
            return self._fmt_time
        if '[错误]' in text or 'error' in tl:
            return self._fmt_error
        if '[警告]' in text or 'warning' in tl:
            return self._fmt_warn
        if '执行命令' in text or '命令执行完成' in text:
            return self._fmt_cmd
        if '成功' in text or 'success' in tl:
            return self._fmt_ok
        return self._fmt_default

    def append_output(self, text):
        """追加输出（可能含多行的批量文本）"""
        cursor = self.textCursor()
        cursor.movePosition(cursor.MoveOperation.End)
        self.setTextCursor(cursor)

        for line in text.split('\n'):
            if not line and text.endswith('\n'):
                continue
            fmt = self._pick_fmt(line)
            cursor.insertText(line + '\n', fmt)

        self.ensureCursorVisible()

        if self.console_window and self.console_window.isVisible():
            self.console_window.append_output(text)

    def open_window(self):
        """打开独立控制台窗口"""
        if not self.console_window:
            self.console_window = ConsoleWindow(self.parent())

        self.console_window.sync_content(self.toPlainText())
        self.console_window.show()
        self.console_window.raise_()
        self.console_window.activateWindow()

    def clear_output(self):
        """清空输出"""
        self.clear()
        if self.console_window:
            self.console_window.console_text.clear()
