#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
VWED.log 模块 - 日志系统
"""

import asyncio
import threading
from concurrent.futures import ThreadPoolExecutor
from ..script_websocket_service import get_websocket_manager
from utils.logger import get_logger

logger = get_logger("services.script_log_module")


class VWEDLogModule:
    """VWED.log 模块 - 日志系统"""
    
    def __init__(self, script_id: str):
        self.script_id = script_id
        self.websocket_manager = get_websocket_manager()
    
    async def info(self, message: str, **kwargs):
        """输出信息日志"""
        print(f"🔄 [{self.script_id}script_idscript_idscript_id] INFO: {message}")
        logger.info(f"WebSocket推送日志 [{self.script_id}] INFO: {message}")
        await self.websocket_manager.broadcast_script_log(
            self.script_id, "INFO", message, **kwargs
        )
    
    async def warning(self, message: str, **kwargs):
        """输出警告日志"""
        print(f"🔄 [{self.script_id}] WARNING: {message}")
        logger.warning(f"WebSocket推送日志 [{self.script_id}] WARNING: {message}")
        await self.websocket_manager.broadcast_script_log(
            self.script_id, "WARNING", message, **kwargs
        )
    
    async def error(self, message: str, **kwargs):
        """输出错误日志"""
        print(f"🔄 [{self.script_id}] ERROR: {message}")
        logger.error(f"WebSocket推送日志 [{self.script_id}] ERROR: {message}")
        await self.websocket_manager.broadcast_script_log(
            self.script_id, "ERROR", message, **kwargs
        )
    
    async def debug(self, message: str, **kwargs):
        """输出调试日志"""
        print(f"🔄 [{self.script_id}] DEBUG: {message}")
        logger.debug(f"WebSocket推送日志 [{self.script_id}] DEBUG: {message}")
        await self.websocket_manager.broadcast_script_log(
            self.script_id, "DEBUG", message, **kwargs
        )
    
    def sync_info(self, message: str, **kwargs):
        """同步方式输出信息日志"""
        self._run_async_safely(self.info(message, **kwargs))
    
    def sync_warning(self, message: str, **kwargs):
        """同步方式输出警告日志"""
        self._run_async_safely(self.warning(message, **kwargs))
    
    def sync_error(self, message: str, **kwargs):
        """同步方式输出错误日志"""
        self._run_async_safely(self.error(message, **kwargs))
    
    def sync_debug(self, message: str, **kwargs):
        """同步方式输出调试日志"""
        self._run_async_safely(self.debug(message, **kwargs))
    
    def _run_async_safely(self, coro):
        """安全地运行异步协程"""
        def run_in_thread():
            """在新线程中运行异步代码"""
            try:
                print(f"🔧 [{self.script_id}] 在新线程中运行日志推送")
                # 创建新的事件循环
                loop = asyncio.new_event_loop()
                asyncio.set_event_loop(loop)
                loop.run_until_complete(coro)
                loop.close()
                print(f"✅ [{self.script_id}] 日志推送线程执行完成")
            except Exception as e:
                print(f"❌ [{self.script_id}] 日志推送线程失败: {e}")
                logger.error(f"日志推送线程失败 [{self.script_id}]: {e}")
        
        try:
            # 尝试获取当前事件循环
            asyncio.get_running_loop()
            print(f"🔄 [{self.script_id}] 使用现有事件循环推送日志")
            # 如果有事件循环，创建任务
            asyncio.create_task(coro)
        except RuntimeError:
            print(f"🆕 [{self.script_id}] 没有事件循环，创建新线程推送日志")
            # 没有运行的事件循环，在新线程中运行
            thread = threading.Thread(target=run_in_thread, daemon=True)
            thread.start()
        except Exception as e:
            print(f"❌ [{self.script_id}] 日志推送失败: {e}")
            logger.error(f"日志推送失败 [{self.script_id}]: {e}")