"""Vulnerability mixin for EAP/802.1x findings.

Encapsulates evaluation and persistence of EAP-related vulnerability evidence.
"""
from __future__ import annotations

import csv
from scapy.all import get_if_hwaddr

from ptnetinspector.utils.ip_utils import has_additional_data


class EAPMixin:
    def store_eap_vulnerability(self) -> None:
        existing_rows = self._load_existing_rows()
        self.smac = get_if_hwaddr(self.interface)

        label = 2
        if self.time_all_file and has_additional_data(self.time_all_file):
            eapol_start_found = False
            eapol_start_timestamp = None
            try:
                with open(self.time_all_file, "r", newline="") as csvfile:
                    reader = csv.DictReader(csvfile)
                    for row in reader:
                        mac = row.get("MAC", "").strip()
                        packet = row.get("packet", "")
                        if mac == self.smac and "type = EAPOL-Start" in packet:
                            eapol_start_found = True
                            eapol_start_timestamp = row.get("time", "")
                            break

                if eapol_start_found:
                    label = 1
                    with open(self.time_all_file, "r", newline="") as csvfile:
                        reader = csv.DictReader(csvfile)
                        for row in reader:
                            mac = row.get("MAC", "").strip()
                            packet = row.get("packet", "")
                            timestamp = row.get("time", "")

                            if mac != self.smac and "EAP" in packet:
                                if not eapol_start_timestamp or timestamp >= eapol_start_timestamp:
                                    label = 0
                                    break
            except (FileNotFoundError, KeyError):
                label = 2

        network_row = (
            "Network",
            "",
            "802.1x",
            "",
            "PTV-NET-NET-MISCONF-8021X",
            "Network does not have 802.1x deployed",
            str(label),
        )

        self._add_vuln_if_new(network_row, existing_rows, [])
        self._write_vulnerabilities([self._create_vuln_row(network_row)])
