"""Custom log handlers."""

import logging
import logging.handlers
from pathlib import Path
from typing import Optional

from src.core.constants import PATHS


class RotatingFileHandler(logging.handlers.RotatingFileHandler):
    """Rotating file handler with automatic directory creation."""

    def __init__(
        self,
        filename: str,
        max_bytes: int = 10485760,  # 10MB
        backup_count: int = 5,
        encoding: Optional[str] = "utf-8",
    ):
        """
        Initialize rotating file handler.

        Args:
            filename: Log file path
            max_bytes: Maximum file size before rotation
            backup_count: Number of backup files to keep
            encoding: File encoding
        """
        # Ensure directory exists
        log_path = Path(filename)
        log_path.parent.mkdir(parents=True, exist_ok=True)

        super().__init__(
            filename=str(log_path),
            maxBytes=max_bytes,
            backupCount=backup_count,
            encoding=encoding,
        )


class ErrorFileHandler(RotatingFileHandler):
    """Handler specifically for error-level logs."""

    def __init__(
        self,
        filename: str = str(PATHS["logs"] / "errors" / "exceptions.log"),
        max_bytes: int = 10485760,
        backup_count: int = 5,
    ):
        """
        Initialize error file handler.

        Args:
            filename: Log file path
            max_bytes: Maximum file size before rotation
            backup_count: Number of backup files to keep
        """
        super().__init__(filename, max_bytes, backup_count)
        self.setLevel(logging.ERROR)


class DatabaseHandler(logging.Handler):
    """Handler for storing critical logs in database (placeholder)."""

    def __init__(self):
        """Initialize database handler."""
        super().__init__()
        self.setLevel(logging.CRITICAL)

    def emit(self, record: logging.LogRecord) -> None:
        """
        Emit log record to database.

        Args:
            record: Log record to store
        """
        # TODO: Implement database storage
        # This would store critical logs in a database table
        pass

