import logging

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

logger = logging.getLogger(__name__)


class UnpackDependency(Dependency):
    """
    Base class for dependencies that are installed from fai-cacher.
    Handles download and extraction.
    """

    download_path: str

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

        self.installation_path.mkdir()
        download_and_extract_cmd = (
            f"curl -L {self.download_path} -o - | ( cd {self.installation_path} ; tar --zstd -x)"  # noqa: E501
        )

        if not run_cmd(download_and_extract_cmd).success:
            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

    def add_download_path(self, download_path: str) -> "UnpackDependency":
        self.download_path = download_path
        return self
