"""
Logging configuration for FoundryMatch SaaS
Suppresses noisy debug messages from libraries
"""

import logging
import os
import sys
from pathlib import Path

from .observability.gcp_logging import (
    PIIRedactionFilter,
    ContextInjectingFilter,
    GCPJSONFormatter,
)

def configure_logging(log_level="INFO", log_dir=None):
    """
    Configure logging for the application.

    Args:
        log_level: The default logging level (INFO, DEBUG, WARNING, ERROR)
        log_dir: Directory for log files (creates logs/ in current dir if None)
    """
    is_cloud_run = os.environ.get("K_SERVICE") is not None

    pii_filter = PIIRedactionFilter()
    context_filter = ContextInjectingFilter()

    handlers = []

    # Create console handler (always)
    if is_cloud_run:
        console_formatter = GCPJSONFormatter()
    else:
        # Show correlation IDs in local dev output for debugging.
        # ContextInjectingFilter always sets these attributes (empty string default).
        console_formatter = logging.Formatter(
            "%(asctime)s - %(name)s - %(levelname)s - [req=%(request_id)s acct=%(account_id)s] %(message)s",
            datefmt="%Y-%m-%d %H:%M:%S",
            defaults={"request_id": "-", "account_id": "-"},
        )

    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setLevel(getattr(logging, log_level))
    console_handler.setFormatter(console_formatter)
    handlers.append(console_handler)

    # File handlers only when NOT on Cloud Run (stdout → Cloud Logging is sufficient)
    if not is_cloud_run:
        if log_dir is None:
            log_dir = Path(__file__).parent / "logs"
        log_dir = Path(log_dir)
        log_dir.mkdir(exist_ok=True)

        file_formatter = logging.Formatter(
            "%(asctime)s - %(name)s - %(levelname)s - [%(filename)s:%(lineno)d] - %(message)s",
            datefmt="%Y-%m-%d %H:%M:%S",
        )

        file_handler = logging.FileHandler(log_dir / "fmatch.log", mode="a")
        file_handler.setLevel(logging.DEBUG)
        file_handler.setFormatter(file_formatter)
        handlers.append(file_handler)

        error_handler = logging.FileHandler(log_dir / "fmatch_errors.log", mode="a")
        error_handler.setLevel(logging.ERROR)
        error_handler.setFormatter(file_formatter)
        handlers.append(error_handler)

    for handler in handlers:
        handler.addFilter(pii_filter)
        handler.addFilter(context_filter)

    # Configure root logger
    root_logger = logging.getLogger()
    root_logger.setLevel(logging.DEBUG)
    root_logger.handlers.clear()
    for handler in handlers:
        root_logger.addHandler(handler)

    # Suppress noisy libraries
    noisy_loggers = {
        "multipart": logging.INFO,
        "multipart.multipart": logging.INFO,
        "uvicorn": logging.INFO,
        "uvicorn.access": logging.INFO,
        "uvicorn.error": logging.INFO,
        "sqlalchemy": logging.WARNING,
        "sqlalchemy.engine": logging.WARNING,
        "sqlalchemy.pool": logging.WARNING,
        "sqlalchemy.dialects": logging.WARNING,
        "sqlalchemy.orm": logging.WARNING,
        "watchfiles": logging.WARNING,
        "httpx": logging.WARNING,
        "httpcore": logging.WARNING,
        "redis": logging.WARNING,
        "rq": logging.INFO,
        "aioredis": logging.WARNING,
        "asyncio": logging.WARNING,
        "concurrent": logging.WARNING,
        "urllib3": logging.WARNING,
        "PIL": logging.WARNING,
        "matplotlib": logging.WARNING,
        "parso": logging.WARNING,
    }

    for logger_name, level in noisy_loggers.items():
        logger = logging.getLogger(logger_name)
        logger.setLevel(level)
        logger.propagate = False
        logger.handlers.clear()
        logger.addHandler(console_handler)

    # Configure our application loggers
    app_loggers = [
        "fmatch",
        "fmatch.saas",
        "fmatch.saas.api",
        "fmatch.saas.ml",
        "fmatch.core",
        "fmatch.api",
    ]

    for logger_name in app_loggers:
        logger = logging.getLogger(logger_name)
        logger.setLevel(getattr(logging, log_level))
        logger.propagate = False
        logger.handlers.clear()
        for handler in handlers:
            logger.addHandler(handler)

    return root_logger


def get_logger(name: str) -> logging.Logger:
    """
    Get a logger instance with the given name.

    Args:
        name: Logger name (usually __name__)

    Returns:
        Configured logger instance
    """
    return logging.getLogger(name)


# Configure on import if running as main module
if __name__ != "__main__":
    # Avoid auto-config during tests to keep pytest capture stable.
    if os.getenv("FM_TEST_MODE") != "1" and os.getenv("FM_UNIT_TEST") != "1":
        if not logging.getLogger().handlers:
            configure_logging()
