# -*- coding: utf-8 -*-
# @Project: auto_test
# @Description: 
# @Time   : 2023-04-05 12:40
# @Author : 毛鹏
import threading
from multiprocessing import Lock as ProcessLock
from contextlib import nullcontext

from ..decorator import singleton
from ..log_collector._log_control import LogHandler


@singleton
class Log:
    def __init__(self, log_path, is_debug, concurrency_mode='single'):
        """
        初始化日志系统
        
        Args:
            log_path: 日志文件路径
            is_debug: 是否启用debug日志
            concurrency_mode: 并发模式
                - 'single': 单线程模式（默认，无锁，性能最优）
                - 'thread': 多线程模式（使用threading.Lock）
                - 'process': 多进程模式（使用multiprocessing.Lock）
        """
        self.log_path = log_path
        self.is_debug = is_debug
        self.concurrency_mode = concurrency_mode
        
        # 根据并发模式选择合适的锁机制
        if concurrency_mode == 'thread':
            self.lock = threading.Lock()
        elif concurrency_mode == 'process':
            self.lock = ProcessLock()
        else:  # single
            self.lock = nullcontext()  # 无锁，零性能开销
        
        self.DEBUG = LogHandler(fr"{log_path}\debug-log.log", 'debug', concurrency_mode)
        self.INFO = LogHandler(fr"{log_path}\info-log.log", 'info', concurrency_mode)
        self.WARNING = LogHandler(fr"{log_path}\warning-log.log", 'warning', concurrency_mode)
        self.ERROR = LogHandler(fr"{log_path}\error-log.log", 'error', concurrency_mode)
        self.CRITICAL = LogHandler(fr"{log_path}\critical-log.log", 'critical', concurrency_mode)

    def _log(self, level, msg):
        log_file = {
            'debug': self.DEBUG.logger,
            'info': self.INFO.logger,
            'warning': self.WARNING.logger,
            'error': self.ERROR.logger,
            'critical': self.CRITICAL.logger,
        }[level]
        
        # 单线程模式下使用nullcontext，无锁开销
        with self.lock:
            log_file.log(self.DEBUG.level_relations[level], str(msg))

    def set_debug(self, is_debug: bool):
        self.is_debug = is_debug

    def debug(self, msg: str):
        if self.is_debug:
            self._log('debug', msg)

    def info(self, msg: str):
        self._log('info', msg)

    def warning(self, msg: str):
        self._log('warning', msg)

    def error(self, msg: str):
        self._log('error', msg)

    def critical(self, msg: str):
        self._log('critical', msg)


def set_log(log_path, is_debug=False, concurrency_mode='single'):
    """
    创建日志实例
    
    Args:
        log_path: 日志文件路径
        is_debug: 是否启用debug日志，默认False
        concurrency_mode: 并发模式，默认'single'
            - 'single': 单线程模式（无锁，性能最优）
            - 'thread': 多线程模式
            - 'process': 多进程模式
    
    Returns:
        Log实例
    """
    log = Log(log_path, is_debug, concurrency_mode)
    return log


__all__ = ['set_log']
