"""Log file management service for reading, cleaning, and monitoring logs."""

from __future__ import annotations

import anyio

from mm_base6.config import Config


class LogfileService:
    """Service for managing application and access log files.

    Provides operations to read, clean, and get size information for
    the framework's log files. Handles both application logs (Python logging)
    and access logs (HTTP requests from uvicorn/FastAPI).
    """

    def __init__(self, config: Config) -> None:
        """Initialize log file service with paths from configuration."""
        self.logfile_app = anyio.Path(config.data_dir / "app.log")
        self.logfile_access = anyio.Path(config.data_dir / "access.log")

    def _get_path(self, file: str) -> anyio.Path:
        """Resolve log file type to its path.

        Args:
            file: Log file type, either "app" or "access"

        Returns:
            Path to the requested log file

        Raises:
            ValueError: If file type is not "app" or "access"

        """
        if file == "app":
            return self.logfile_app
        if file == "access":
            return self.logfile_access
        raise ValueError(f"Unknown logfile: {file}")

    async def read_logfile(self, file: str) -> str:
        """Read the contents of a log file.

        Args:
            file: Log file type, either "app" or "access"

        Returns:
            Log file contents, or empty string if file doesn't exist yet

        Raises:
            ValueError: If file type is not "app" or "access"

        """
        path = self._get_path(file)
        try:
            return await path.read_text(encoding="utf-8")
        except FileNotFoundError:
            return ""

    async def clean_logfile(self, file: str) -> None:
        """Clear the contents of a log file.

        Args:
            file: Log file type, either "app" or "access"

        Raises:
            ValueError: If file type is not "app" or "access"

        """
        path = self._get_path(file)
        await path.write_text("", encoding="utf-8")

    async def get_logfile_size(self, file: str) -> int:
        """Get the size of a log file in bytes.

        Args:
            file: Log file type, either "app" or "access"

        Returns:
            File size in bytes, or 0 if file doesn't exist yet

        Raises:
            ValueError: If file type is not "app" or "access"

        """
        path = self._get_path(file)
        try:
            return (await path.stat()).st_size
        except FileNotFoundError:
            return 0
