"""Console 管理器 - 统一管理 Rich Console"""

import logging
from typing import Optional

from rich.console import Console
from rich.theme import Theme

logger = logging.getLogger("agent")

# 自定义主题
CUSTOM_THEMES = Theme(
    {
        "repr.str": "cyan",
        "repr.bool": "magenta",
        "repr.number": "green",
        "heading": "bold cyan",
        "subheading": "bold blue",
        "success": "bold green",
        "warning": "bold yellow",
        "error": "bold red",
        "info": "blue",
    }
)


def _safe_encode(text: str) -> str:
    """安全编码文本，处理代理字符"""
    try:
        # 尝试直接编码
        text.encode('utf-8')
        return text
    except UnicodeEncodeError:
        # 移除代理字符
        return text.encode('utf-8', errors='replace').decode('utf-8')


class ConsoleManager:
    """Rich Console 管理器

    提供统一的 Console 实例，支持：
    - 富文本输出
    - 彩色日志
    - 面板布局
    """

    _instance: Optional["ConsoleManager"] = None
    _console: Optional[Console] = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self):
        if self._console is None:
            # 禁用 emoji 以避免 Unicode 编码问题
            self._console = Console(
                theme=CUSTOM_THEMES,
                emoji=False,  # 禁用 emoji 避免代理字符问题
                markup=True,
            )

    @property
    def console(self) -> Console:
        """获取 Console 实例"""
        return self._console

    def print(self, *args, **kwargs):
        """打印内容，带异常处理"""
        try:
            self._console.print(*args, **kwargs)
        except UnicodeEncodeError:
            # 回退到安全打印
            safe_args = []
            for arg in args:
                if isinstance(arg, str):
                    safe_args.append(_safe_encode(arg))
                else:
                    safe_args.append(arg)
            print(*safe_args, **kwargs)

    def print_markdown(self, text: str):
        """打印 Markdown 文本"""
        from rich.markdown import Markdown

        try:
            md = Markdown(text)
            self._console.print(md)
        except UnicodeEncodeError:
            # 回退到普通打印
            print(text)

    def print_code(self, code: str, language: str = "python"):
        """打印带语法高亮的代码"""
        from rich.syntax import Syntax

        try:
            syntax = Syntax(code, language, theme="monokai", line_numbers=True)
            self._console.print(syntax)
        except UnicodeEncodeError:
            # 回退到普通打印
            print(code)

    def print_panel(
        self,
        content: str,
        title: str = "",
        border_style: str = "blue",
        style: str = "",
    ):
        """打印面板"""
        from rich.panel import Panel

        try:
            panel = Panel(
                content,
                title=title,
                border_style=border_style,
                style=style,
                expand=False,
            )
            self._console.print(panel)
        except UnicodeEncodeError:
            # 回退到普通打印
            if title:
                print(f"=== {title} ===")
            print(content)

    def print_table(
        self,
        data: list[list[str]],
        headers: Optional[list[str]] = None,
        title: str = "",
        show_lines: bool = True,
    ):
        """打印表格"""
        from rich.table import Table

        try:
            table = Table(title=title, show_lines=show_lines)

            if headers:
                for header in headers:
                    table.add_column(header, style="cyan")

            for row in data:
                table.add_row(*row)

            self._console.print(table)
        except UnicodeEncodeError:
            # 回退到普通打印
            if title:
                print(f"=== {title} ===")
            if headers:
                print(" | ".join(headers))
                print("-" * 40)
            for row in data:
                print(" | ".join(row))

    def print_error(self, message: str):
        """打印错误信息"""
        from rich.panel import Panel

        try:
            panel = Panel(
                f"[error]{message}[/error]",
                title="错误",
                border_style="red",
            )
            self._console.print(panel)
        except UnicodeEncodeError:
            print(f"[错误] {message}")

    def print_success(self, message: str):
        """打印成功信息"""
        try:
            self._console.print(f"[success]✓ {message}[/success]")
        except UnicodeEncodeError:
            print(f"[成功] {message}")

    def print_warning(self, message: str):
        """打印警告信息"""
        try:
            self._console.print(f"[warning]⚠ {message}[/warning]")
        except UnicodeEncodeError:
            print(f"[警告] {message}")

    def print_info(self, message: str):
        """打印提示信息"""
        try:
            self._console.print(f"[info]ℹ {message}[/info]")
        except UnicodeEncodeError:
            print(f"[信息] {message}")

    def clear(self):
        """清空控制台"""
        self._console.clear()

    def input(self, prompt: str = "") -> str:
        """带样式的输入提示"""
        try:
            return self._console.input(prompt)
        except UnicodeEncodeError:
            return input(prompt)


# 全局实例
_default_console_manager: Optional[ConsoleManager] = None


def get_console_manager() -> ConsoleManager:
    """获取全局 ConsoleManager 实例"""
    global _default_console_manager
    if _default_console_manager is None:
        _default_console_manager = ConsoleManager()
    return _default_console_manager
