import subprocess

from pre_wigs_validation.enums import ValidationEnforcement, ValidationResult
from pre_wigs_validation.instance import ValidationInstance
from pre_wigs_validation.dataclasses import ValidationOutput
from pre_wigs_validation.utils import check_validation_config


class SudoersConfiguration:
    """Validate that sudoers is properly configured."""

    validation = "Sudoers Configuration"
    enforcement = ValidationEnforcement.RECOMMENDED

    @classmethod
    def validate(
        cls, *, enabled: bool = True, instance: ValidationInstance
    ) -> ValidationOutput:

        """
        Parameters:
        enabled (bool): whether or not to run this validation function
        instance (ValidationInstance): the instance object being validated

        Returns:
        ValidationOutput: output of validation
        """

        if not enabled:
            return ValidationOutput(
                validation=cls.validation,
                result=ValidationResult.NOT_RUN,
                enforcement=cls.enforcement,
            )

        fail_message = "Following parameter - requiretty is set in :"
        verbose_message = (
            'To successfully run WIGs automation, this parameter "Defaults requiretty" has to be changed to : Defaults !requiretty'
        )
        
        require_tty_enabled = False

        with open("/etc/sudoers") as file:
            for line in file.readlines():
                if line.startswith("Defaults") and " requiretty" in line:
                    require_tty_enabled = True

        if require_tty_enabled:
          fail_message += "/etc/sudoers file."

        config = check_validation_config(
            default_params=cls.validate.__kwdefaults__, local_params=locals()
        )

        if not require_tty_enabled:
            return ValidationOutput(
                validation=cls.validation,
                result=ValidationResult.PASS,
                enforcement=cls.enforcement,
                config=config,
            )

        return ValidationOutput(
            validation=cls.validation,
            result=ValidationResult.FAIL,
            enforcement=cls.enforcement,
            config=config,
            message=fail_message,
            verbose_message=verbose_message
        )
