from __future__ import annotations

import logging
import logging.config
from pathlib import Path


def build_log_path(explicit_path: str | None = None) -> Path:
    """Resolve the CLI log file destination."""

    if explicit_path:
        return Path(explicit_path).expanduser().resolve()
    return (Path.cwd() / ".dspyteach" / "logs" / "run.log").resolve()


def configure_logging(
    *,
    log_path: str | None = None,
    level: str = "INFO",
    console: bool = True,
) -> Path:
    """Configure console and rotating file logging for CLI runs."""

    resolved_path = build_log_path(log_path)
    resolved_path.parent.mkdir(parents=True, exist_ok=True)

    handlers: dict[str, dict[str, object]] = {
        "file": {
            "class": "logging.handlers.RotatingFileHandler",
            "filename": str(resolved_path),
            "maxBytes": 2_000_000,
            "backupCount": 5,
            "encoding": "utf-8",
            "formatter": "standard",
            "level": level,
        }
    }
    root_handlers = ["file"]

    if console:
        handlers["console"] = {
            "class": "logging.StreamHandler",
            "formatter": "standard",
            "level": level,
        }
        root_handlers.append("console")

    logging.config.dictConfig(
        {
            "version": 1,
            "disable_existing_loggers": False,
            "formatters": {
                "standard": {
                    "format": "%(asctime)s %(levelname)s [%(name)s] %(message)s",
                    "datefmt": "%Y-%m-%d %H:%M:%S",
                }
            },
            "handlers": handlers,
            "root": {
                "level": level,
                "handlers": root_handlers,
            },
        }
    )

    return resolved_path
