#!/usr/bin/python3


import logging
import shutil

from slpkg.config import config_load
from slpkg.views.display import View

logger = logging.getLogger(__name__)


class Cleanings:  # pylint: disable=[R0903,R0902]
    """Cleans the logs from packages."""

    def __init__(self) -> None:
        logger.debug("Initializing Cleanings module.")
        self.tmp_slpkg = config_load.tmp_slpkg
        self.build_path = config_load.build_path
        self.bold = config_load.bold
        self.red = config_load.red
        self.endc = config_load.endc

        self.view = View()
        logger.debug("Cleanings module initialized. tmp_slpkg: %s, build_path: %s", self.tmp_slpkg, self.build_path)

    def tmp(self) -> None:
        """Delete files and folders in /tmp/slpkg/ folder."""
        logger.info("Starting deletion of local data in %s.", self.tmp_slpkg)
        print("Cached files to delete:\n")

        files = list(self.tmp_slpkg.rglob("*"))
        if not files:
            logger.info("No files or folders found to delete in %s.", self.tmp_slpkg)
            print("No files or folders to delete.\n")
            return

        for file in files:
            print(f"  {file}")
            logger.debug("File found for deletion: %s", file)

        # Symlink protection: refuse to delete if the resolved path is outside /tmp/.
        resolved = self.tmp_slpkg.resolve()
        if not str(resolved).startswith("/tmp/"):
            print(f"{self.red}Error{self.endc}: Refusing to delete '{resolved}' — path is outside /tmp/.\n")
            logger.error("Refusing to delete: resolved path '%s' is outside /tmp/", resolved)
            return

        print(f"\n{self.bold}{self.red}WARNING{self.endc}: All files and folders will be permanently deleted.")
        logger.warning("User warned about deletion of all files/folders in %s.", self.tmp_slpkg)

        self.view.question()

        try:
            shutil.rmtree(self.tmp_slpkg)
            logger.info("Successfully removed folder: %s", self.tmp_slpkg)
        except OSError as e:
            logger.error("Failed to remove folder '%s': %s", self.tmp_slpkg, e, exc_info=True)
            print(f"{self.red}Error{self.endc}: Failed to remove {self.tmp_slpkg}\n")
            return

        try:
            self.build_path.mkdir(parents=True, exist_ok=True)
            logger.info("Successfully created build directory: %s", self.build_path)
        except OSError as e:
            logger.error("Failed to create build directory '%s': %s", self.build_path, e, exc_info=True)
            print(f"{self.red}Error{self.endc}: Failed to create {self.build_path}\n")
            return

        print("Successfully cleared!\n")
        logger.info("Local data clearing process completed.")
