# -*- coding: utf-8 -*-
"""GUI logging setup."""

import logging
from datetime import datetime

def setup_logging():
    """配置日志系统。日志属于软件配置，与软件一起走（存于 AppData/ServerManager/logs）。"""
    # 创建根日志器
    logger = logging.getLogger('server_manager')
    logger.setLevel(logging.DEBUG)
    logger.propagate = False
    if logger.handlers:
        return logger

    log_format = '%(asctime)s [%(levelname)s] %(name)s: %(message)s'
    date_format = '%Y-%m-%d %H:%M:%S'

    # 控制台处理器 - 只记录警告及以上
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.WARNING)
    console_handler.setFormatter(logging.Formatter(log_format, date_format))
    logger.addHandler(console_handler)

    try:
        from models.app_config import get_app_log_dir
        log_dir = get_app_log_dir()
        log_file = log_dir / f"server_manager_{datetime.now().strftime('%Y%m%d')}.log"

        file_handler = logging.FileHandler(log_file, encoding='utf-8')
        file_handler.setLevel(logging.DEBUG)
        file_handler.setFormatter(logging.Formatter(log_format, date_format))
        logger.addHandler(file_handler)

        # 清理旧日志（保留最近7天）
        try:
            for old_log in log_dir.glob('server_manager_*.log'):
                if old_log != log_file:
                    file_time = datetime.fromtimestamp(old_log.stat().st_mtime)
                    if (datetime.now() - file_time).days > 7:
                        old_log.unlink()
        except Exception:
            pass
    except Exception:
        pass
    
    return logger


logger = setup_logging()
