from __future__ import annotations

import logging
import os
import sys
from datetime import datetime, timezone
from pathlib import Path


def resolve_log_level(
    *,
    env_name: str = "AUTOPROMPTLAB_LOG_LEVEL",
    default: int = logging.INFO,
) -> int:
    value = os.getenv(env_name)
    if not value:
        return default
    value = value.strip().upper()
    if value == "WARN":
        value = "WARNING"
    level = getattr(logging, value, None)
    if isinstance(level, int):
        return level
    try:
        return int(value)
    except ValueError:
        return default


def setup_logging(
    *,
    log_dir: Path,
    level: int = logging.INFO,
    console: bool = True,
    filename_prefix: str = "run",
) -> tuple[Path, Path]:
    log_dir.mkdir(parents=True, exist_ok=True)
    timestamp = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")
    log_path = log_dir / f"{filename_prefix}_{timestamp}.log"
    noisy_log_path = log_dir / f"{filename_prefix}_{timestamp}.verbose.log"

    root_logger = logging.getLogger()
    root_logger.setLevel(level)

    formatter = logging.Formatter("%(asctime)s %(levelname)s %(name)s: %(message)s")

    if console and not any(isinstance(h, logging.StreamHandler) for h in root_logger.handlers):
        # Use UTF-8 encoding for console output on Windows to handle Unicode characters
        stream = sys.stdout
        if hasattr(stream, 'reconfigure'):
            try:
                stream.reconfigure(encoding='utf-8', errors='replace')
            except Exception:
                pass  # Ignore if reconfigure fails (e.g., non-standard streams)
        stream_handler = logging.StreamHandler(stream)
        stream_handler.setFormatter(formatter)
        root_logger.addHandler(stream_handler)

    for handler in list(root_logger.handlers):
        if getattr(handler, "_autopromptlab_file", False):
            root_logger.removeHandler(handler)
            handler.close()

    file_handler = logging.FileHandler(log_path, encoding="utf-8")
    file_handler.setFormatter(formatter)
    file_handler._autopromptlab_file = True
    root_logger.addHandler(file_handler)

    noisy_handler = logging.FileHandler(noisy_log_path, encoding="utf-8")
    noisy_handler.setFormatter(formatter)
    noisy_handler._autopromptlab_noisy_file = True

    noisy_loggers = [logging.getLogger("httpx"), logging.getLogger("autogen_core.events")]
    old_noisy_handlers: list[logging.Handler] = []
    for noisy_logger in noisy_loggers:
        for handler in list(noisy_logger.handlers):
            if getattr(handler, "_autopromptlab_noisy_file", False):
                noisy_logger.removeHandler(handler)
                old_noisy_handlers.append(handler)
        noisy_logger.addHandler(noisy_handler)
        noisy_logger.propagate = False

    for handler in old_noisy_handlers:
        handler.close()

    return log_path, noisy_log_path
