import logging

from test_automation_suite.dependencies.dependency import Dependency
from test_automation_suite.utility.cmd import execute_cmds

logger = logging.getLogger(__name__)


class AptDependency(Dependency):
    """
    Base class for dependencies that are installed via APT.
    Handles standard apt install flow and sets up the installation path.
    """

    def _install(self) -> bool:
        """
        Install the package using apt-get and ensure the installation directory exists.
        Returns True on success, False otherwise.
        """
        logger.info("Starting APT installation for %s", self.name)

        commands = [
            # Update package lists
            "sudo apt-get update -y",
            # Install package
            f"sudo apt-get install -y {self.name}",
            # Create installation directory
            f"mkdir -p '{self.installation_path}'",
            # Fix ownership
            f"chown -R root:root '{self.installation_path}'",
        ]

        if not execute_cmds(commands):
            return False

        # Verify installation directory
        if not self.installation_path.is_dir():
            logger.error(
                "%s: installation path %s not found after install",
                self.name,
                self.installation_path,
            )
            return False

        logger.info("%s installed successfully.", self.name)
        return True
