"""
日誌配置
"""
import logging
import sys
from pathlib import Path
from pythonjsonlogger import jsonlogger


def setup_logging():
    """設置日誌系統"""
    # 延遲導入避免循環依賴
    from app.core.config import settings

    # 創建日誌目錄
    log_file = Path(settings.LOG_FILE)
    log_file.parent.mkdir(parents=True, exist_ok=True)

    # 根日誌器
    root_logger = logging.getLogger()
    root_logger.setLevel(getattr(logging, settings.LOG_LEVEL))

    # 格式化器
    formatter = logging.Formatter(
        "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S",
    )

    # JSON 格式化器 (生產環境)
    json_formatter = jsonlogger.JsonFormatter(
        "%(asctime)s %(name)s %(levelname)s %(message)s"
    )

    # 控制台處理器
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setLevel(logging.INFO)
    console_handler.setFormatter(formatter)

    # 文件處理器
    file_handler = logging.FileHandler(log_file, encoding="utf-8")
    file_handler.setLevel(logging.DEBUG)

    if settings.ENVIRONMENT == "production":
        file_handler.setFormatter(json_formatter)
    else:
        file_handler.setFormatter(formatter)

    # 添加處理器
    root_logger.addHandler(console_handler)
    root_logger.addHandler(file_handler)

    # 設置第三方日誌級別
    logging.getLogger("uvicorn").setLevel(logging.INFO)
    logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
