from logging import Logger
from typing import override

from test_automation_suite.checks.check import Check
from test_automation_suite.core.context import Context
from test_automation_suite.core.task import Step, StepResult
from test_automation_suite.utility.cmd import run_cmd_t


class CheckAllDkmsInstalled(Check):
    @override
    def steps(self) -> list[Step]:
        return [*super().steps(), self.step_check_all]

    def step_check_all(self, _context: Context, logger: Logger) -> StepResult:
        dkms_modules = {}

        cmd = "dkms status"
        logger.debug("checking dkms status (%s)", cmd)
        dkms_status_run, error = run_cmd_t(cmd)
        logger.debug("dkms status output: %s", dkms_status_run)
        if error:
            logger.error("failed to check dkms status: %s", error)
            return StepResult(success=False)

        success: bool = True
        for line in dkms_status_run.splitlines():
            if line.isspace():
                continue
            if "failed" in line or "installed" not in line:
                success = False
                logger.error("dkms module error: %s", line.strip())
            dkms_module, dkms_module_version = line.split(",")[0].split("/")
            dkms_module_status = line.split(" ")[-1]
            dkms_modules[dkms_module] = {
                "version": dkms_module_version,
                "status": dkms_module_status,
            }

        return StepResult(
            success=success,
            harvest_data={"dkms_modules": dkms_modules},
        )
