import asyncio
from typing import Dict, Any, Optional

from mineru_flow.internal.config.worker import get_worker_config
from mineru_flow.internal.worker.job_worker import WorkerManager
from mineru_flow.internal.common.logging import get_worker_logger


class SimpleWorkerManager:
    """简化的 Worker 管理器 - 适合命令行应用"""

    def __init__(self):
        self.worker_manager: Optional[WorkerManager] = None
        self.worker_task: Optional[asyncio.Task] = None
        self.config = get_worker_config()
        self._is_running = False
        self.logger = get_worker_logger().bind(manager="simple")

    async def start(self) -> None:
        """启动 Worker 系统"""
        if self._is_running:
            self.logger.warning("Worker 系统已在运行")
            return

        try:
            self.logger.info("🚀 启动 Worker 系统", concurrency=self.config.concurrency)

            # 创建 Worker 管理器
            self.worker_manager = WorkerManager()

            # 在后台任务中启动 Workers
            self.worker_task = asyncio.create_task(self._run_workers())
            self._is_running = True

            self.logger.info("✅ Worker 系统启动成功")

        except Exception as e:
            self.logger.error("❌ Worker 系统启动失败", error=str(e))
            self._is_running = False
            raise

    async def stop(self) -> None:
        """停止 Worker 系统"""
        if not self._is_running:
            return

        try:
            self.logger.info("🛑 正在停止 Worker 系统...")

            # 取消 Worker 任务
            if self.worker_task:
                self.worker_task.cancel()
                try:
                    await self.worker_task
                except asyncio.CancelledError:
                    pass

            # 停止 Worker 管理器
            if self.worker_manager:
                await self.worker_manager.stop_workers()

            self._is_running = False
            self.logger.info("✅ Worker 系统已停止")

        except Exception as e:
            self.logger.error("❌ Worker 系统停止异常", error=str(e))

    async def _run_workers(self) -> None:
        """运行 Worker 系统 - 带重启机制"""
        restart_count = 0
        max_restarts = 3

        while restart_count < max_restarts:
            try:
                if self.worker_manager:
                    self.logger.info(
                        "🔄 启动 Worker 进程", restart_count=restart_count
                    )
                    await self.worker_manager.start_workers()

                # 正常结束，跳出循环
                break

            except asyncio.CancelledError:
                self.logger.info("Worker 系统被取消")
                break

            except Exception as e:
                restart_count += 1
                self.logger.error(
                    "Worker 系统异常",
                    error=str(e),
                    restart_count=restart_count,
                    max_restarts=max_restarts,
                )

                if restart_count < max_restarts:
                    # 等待后重启
                    wait_time = min(5 * restart_count, 30)
                    self.logger.info("等待后重启", wait_time=wait_time)
                    await asyncio.sleep(wait_time)
                else:
                    self.logger.error("Worker 系统重启次数过多，停止重试")
                    self._is_running = False
                    break

    def get_stats(self) -> Dict[str, Any]:
        """获取统计信息"""
        if not self._is_running or not self.worker_manager:
            return {
                "status": "stopped",
                "active_jobs": 0,
                "total_processed": 0,
                "workers": 0,
            }

        all_stats = self.worker_manager.get_all_stats()

        return {
            "status": "running",
            "active_jobs": sum(stats.active_jobs for stats in all_stats),
            "total_processed": sum(stats.total_processed for stats in all_stats),
            "total_errors": sum(stats.total_errors for stats in all_stats),
            "workers": len(all_stats),
            "worker_details": [
                {
                    "worker_id": stats.worker_id,
                    "active_jobs": stats.active_jobs,
                    "total_processed": stats.total_processed,
                    "total_errors": stats.total_errors,
                    "consecutive_errors": stats.consecutive_errors,
                    "last_error": stats.last_error,
                }
                for stats in all_stats
            ],
        }

    @property
    def is_running(self) -> bool:
        """检查 Worker 系统是否在运行"""
        return self._is_running


# 全局单例实例
_simple_manager: Optional[SimpleWorkerManager] = None


def get_simple_manager() -> SimpleWorkerManager:
    """获取简单 Worker 管理器"""
    global _simple_manager
    if _simple_manager is None:
        _simple_manager = SimpleWorkerManager()
    return _simple_manager


async def start_simple_workers():
    """启动简单 Worker 系统"""
    manager = get_simple_manager()
    await manager.start()


async def stop_simple_workers():
    """停止简单 Worker 系统"""
    manager = get_simple_manager()
    await manager.stop()


def get_simple_worker_stats() -> Dict[str, Any]:
    """获取简单 Worker 统计信息"""
    manager = get_simple_manager()
    return manager.get_stats()
