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
from test_automation_suite.utility.network import (
    deactivate_all_connections,
    check_internet_connection,
    remove_connection,
)


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

    def check_lan(self, context: Context, logger: Logger) -> StepResult:
        logger.info("checking lan connection")
        _ = deactivate_all_connections(logger)
        if not self.reconnect_lan(logger):
            return StepResult(success=False)
        if not check_internet_connection(context.config.network_ping_address):
            return StepResult(success=False)
        return StepResult(success=True)

    def reconnect_lan(self, logger: Logger) -> bool:
        logger.info("checking for ethernet devices")
        result, error = run_cmd_t('nmcli -t d | grep "ethernet"')
        if error:
            logger.error("Failed to find ethernet device: %s", error)
            return False
        interface = result.split(":")[0]
        logger.info("interface found: %s", interface)
        con_name = result.split(":")[3].strip()
        _ = remove_connection(con_name)
        cmd = f"nmcli -t c add type ethernet ifname '{interface}' con-name '{con_name}' ipv4.method auto"  # noqa: E501
        result, error = run_cmd_t(cmd)
        if error:
            logger.error("Failed to add ethernet connection: %s", error)
            return False
        cmd = f"nmcli connection up '{con_name}'"
        result, error = run_cmd_t(cmd)
        if error:
            logger.error("Failed to activate LAN connection: %s", error)
            return False
        return True
