"""Structured logging setup for AntiQA."""

from __future__ import annotations

import logging
import sys
from pathlib import Path

from rich.logging import RichHandler

_CONFIGURED = False


def setup_logging(logs_dir: str = "logs/", verbose: bool = False) -> logging.Logger:
    """Configure and return the root 'antiqa' logger.

    - Console output via Rich (colour + formatting)
    - File output to *logs_dir*/antiqa.log
    """
    global _CONFIGURED  # noqa: PLW0603
    logger = logging.getLogger("antiqa")

    if _CONFIGURED:
        return logger

    level = logging.DEBUG if verbose else logging.INFO
    logger.setLevel(level)

    console_handler = RichHandler(
        rich_tracebacks=True,
        show_path=False,
        markup=True,
    )
    console_handler.setLevel(level)
    logger.addHandler(console_handler)

    log_path = Path(logs_dir)
    log_path.mkdir(parents=True, exist_ok=True)
    file_handler = logging.FileHandler(log_path / "antiqa.log")
    file_handler.setLevel(logging.DEBUG)
    file_handler.setFormatter(
        logging.Formatter("%(asctime)s | %(levelname)-8s | %(name)s | %(message)s")
    )
    logger.addHandler(file_handler)

    logger.propagate = False
    _CONFIGURED = True
    return logger


def get_logger(name: str = "antiqa") -> logging.Logger:
    """Get a child logger under the 'antiqa' namespace."""
    return logging.getLogger(name)
