"""
工作空间标签页 - 显示工作空间信息
"""
import os
from typing import Optional
from PySide6.QtWidgets import QVBoxLayout
from PySide6.QtCore import Qt

try:
    from .base_tab import BaseTab
except ImportError:
    from base_tab import BaseTab

try:
    from ..components.markdown_display import MarkdownDisplayWidget
except ImportError:
    try:
        from components.markdown_display import MarkdownDisplayWidget
    except ImportError:
        from PySide6.QtWidgets import QTextEdit
        MarkdownDisplayWidget = QTextEdit

try:
    from ..workspace_manager import WorkspaceManager
except ImportError:
    try:
        from workspace_manager import WorkspaceManager
    except ImportError:
        WorkspaceManager = None


class WorkspaceTab(BaseTab):
    """工作空间标签页 - 显示工作空间详细信息"""

    def __init__(self, workspace_id: str, project_path: Optional[str] = None, parent=None):
        super().__init__(parent)
        self.workspace_id = workspace_id
        self.project_path = project_path
        self.workspace_config = None
        self.stage_template = None

        # 加载工作空间配置
        self._load_workspace_config()

        # 创建UI
        self.create_ui()

    def _load_workspace_config(self):
        """加载工作空间配置"""
        if not WorkspaceManager:
            return

        try:
            manager = WorkspaceManager(self.project_path)
            self.workspace_config = manager.load_workspace_config(self.workspace_id)

            # 加载阶段模板
            if self.workspace_config:
                stage_template_id = self.workspace_config.get('stage_template_id')
                if stage_template_id:
                    self.stage_template = manager.load_stage_template(stage_template_id)
        except Exception:
            # 静默处理加载失败
            self.workspace_config = None
            self.stage_template = None

    def create_ui(self):
        """创建工作空间标签页UI"""
        layout = QVBoxLayout(self)
        layout.setContentsMargins(10, 10, 10, 10)

        # 使用 MarkdownDisplayWidget 显示工作空间信息
        display_widget = MarkdownDisplayWidget()

        # 格式化工作空间信息为Markdown
        markdown_content = self._format_workspace_info()
        display_widget.setMarkdownText(markdown_content)

        layout.addWidget(display_widget)

    def _format_workspace_info(self) -> str:
        """格式化工作空间信息为Markdown文本

        Returns:
            str: 格式化的Markdown文本
        """
        if not self.workspace_config:
            return "## ⚠️ 无法加载工作空间配置\n\n请检查工作空间ID是否正确。"

        parts = []

        # 1. 工作空间基本信息
        parts.append("## 📦 工作空间信息")
        parts.append("")
        parts.append(f"**ID:** `{self.workspace_id}`")

        goal = self.workspace_config.get('goal', '未设置')
        parts.append(f"**目标:** {goal}")

        status = self.workspace_config.get('status', '未知')
        parts.append(f"**状态:** {status}")

        created_at = self.workspace_config.get('created_at', '未知')
        parts.append(f"**创建时间:** {created_at}")

        updated_at = self.workspace_config.get('updated_at', '未知')
        parts.append(f"**更新时间:** {updated_at}")

        parts.append("")

        # 2. 阶段信息
        parts.append("## 📍 阶段信息")
        parts.append("")

        stage_template_id = self.workspace_config.get('stage_template_id', '未设置')
        parts.append(f"**模板:** `{stage_template_id}`")

        current_stage_id = self.workspace_config.get('current_stage_id', '未设置')
        parts.append(f"**当前阶段:** `{current_stage_id}`")

        # 显示当前阶段详细信息
        if self.stage_template and current_stage_id:
            workflow = self.stage_template.get('workflow', {})
            steps = workflow.get('steps', [])

            for step in steps:
                if step.get('id') == current_stage_id:
                    parts.append("")
                    parts.append(f"**阶段标题:** {step.get('title', '未知')}")
                    parts.append(f"**阶段描述:** {step.get('des', '无描述')}")
                    break

        parts.append("")

        # 3. 相关文档列表
        documents = self.workspace_config.get('documents', [])
        if documents:
            parts.append("## 📄 相关文档")
            parts.append("")
            for doc in documents:
                if isinstance(doc, dict):
                    title = doc.get('title', '未命名文档')
                    path = doc.get('path', '')
                    parts.append(f"- **{title}** (`{path}`)")
                else:
                    parts.append(f"- `{doc}`")
            parts.append("")

        # 4. 相关文件列表
        files = self.workspace_config.get('files', [])
        if files:
            parts.append("## 📁 相关文件")
            parts.append("")
            for file_path in files:
                # 只显示文件名
                file_name = os.path.basename(file_path)
                parts.append(f"- `{file_name}` ({file_path})")
            parts.append("")

        return "\n".join(parts)
