"""Logging configuration for yier-agents using loguru."""

import os
import sys
from pathlib import Path

from loguru import logger

# ── 移除 loguru 默认 handler ───────────────────────────────────────────────────
logger.remove()

# ── 日志级别：优先读环境变量，默认 INFO ─────────────────────────────────────────
_LOG_LEVEL = os.getenv("YIER_LOG_LEVEL", "INFO").upper()

# ── 控制台输出（stderr）────────────────────────────────────────────────────────
logger.add(
    sys.stderr,
    level=_LOG_LEVEL,
    format=(
        "<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | "
        "<level>{level: <8}</level> | "
        "<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - "
        "<level>{message}</level>"
    ),
    colorize=True,
)

# ── 文件输出：~/.yier/logs/yier.log（按大小轮转，保留 7 天）────────────────────
_log_dir = Path.home() / ".yier" / "logs"
try:
    _log_dir.mkdir(parents=True, exist_ok=True)
    logger.add(
        _log_dir / "yier.log",
        level="DEBUG",  # 文件记录更详细
        format=(
            "{time:YYYY-MM-DD HH:mm:ss.SSS} | "
            "{level: <8} | "
            "{name}:{function}:{line} - "
            "{message}"
        ),
        rotation="10 MB",
        retention="7 days",
        encoding="utf-8",
        enqueue=True,  # 异步写入，不阻塞主线程
    )
except OSError:
    logger.warning(f"File logging is unavailable, falling back to stderr only: {_log_dir}")

__all__ = ["logger"]
