import logging
import os
from typing import Any, Optional

import nltk


log = logging.getLogger(__name__)


def download_nltk_data() -> None:
    """download required NLTK data if not already present"""
    required_data = [
        ("tokenizers/punkt_tab", "punkt_tab"),
        ("corpora/stopwords", "stopwords"),
    ]

    missing_data = []
    for data_path, download_name in required_data:
        try:
            nltk.data.find(data_path)
        except LookupError:
            missing_data.append(download_name)

    if not missing_data:
        log.info("NLTK data already available")
        return

    log.info(f"downloading NLTK data: {', '.join(missing_data)}")
    for download_name in missing_data:
        nltk.download(download_name, quiet=True)
    log.info("NLTK data download complete")


def setup_logging(
    log_to_screen: bool = True,
    level: int = logging.WARNING,
    filename: str = "default.log",
    path: Optional[str] = None,
) -> None:
    """setup logging with screen or file output"""

    # cleanup existing handlers
    for handler in logging.root.handlers[:]:
        logging.root.removeHandler(handler)

    config = {
        "level": level,
        "format": "%(levelname).1s %(asctime)s [%(funcName)s] %(message)s",
        "datefmt": "%m%d.%H%M%S",
        "force": True,
    }

    if not log_to_screen:
        if path and os.path.exists(path):
            filename = os.path.join(path, filename)
        config.update({"filename": filename, "filemode": "a"})

    logging.basicConfig(**config)


def setup_slogging(
    logger_name: str = "stats_log",
    filename: str = "stats.log",
    path: Optional[str] = None,
    level: int = logging.INFO,
    drive_manager=None,
) -> None:
    """
    create distinct logger to track specific metrics.
    this logger always writes to file and is independent of the main logger.

    Args:
        logger_name: name for the logger
        filename: log filename
        path: directory path for log file
        level: logging level
        drive_manager: optional DriveManager instance for cloud storage

    Returns:
        Logger instance configured for file output
    """
    logger = logging.getLogger(logger_name)

    # only configure if not already configured (handlers exist)
    if not logger.handlers:
        logger.setLevel(level)

        # create formatter
        formatter = logging.Formatter(
            fmt="%(levelname).1s %(asctime)s [%(funcName)s] %(message)s",
            datefmt="%m%d.%H%M%S",
        )

        # determine file path
        if path and os.path.exists(path):
            filepath = os.path.join(path, filename)
        else:
            filepath = filename

        # create file handler
        file_handler = logging.FileHandler(filepath, mode="a")
        file_handler.setLevel(level)
        file_handler.setFormatter(formatter)

        # add handler to logger
        logger.addHandler(file_handler)

        # prevent propagation to root logger (keeps it separate)
        logger.propagate = False

        # store drive_manager reference if provided
        if drive_manager:
            logger._drive_manager = drive_manager
            logger._log_filepath = filepath


def slog(
    status: int,
    record: str,
    track: Any,
    details: Any = "",
    logger_name: str = "stats_log",
) -> None:
    """
    convenience function to log config results in specific format.

    args:
        status: status code (0 for success, non-zero for failure)
        record: record or data category identifier
        track: data aspect or configuration to track
        details: additional details about the result
        logger_name: name of the logger to use
    """
    logger = logging.getLogger(logger_name)

    message = f"|{status}|{record}|{str(track)}|{str(details)}"

    if status == 0:
        logger.info(message)
    else:
        logger.error(message)
