import csv
import os
from io import StringIO

import paramiko
import structlog

logger = structlog.get_logger(__name__)


def _create_edoniq_sftp_client():
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    # Get the private key from the environment variable and convert it to a key object
    private_key_env_var_name = "IT_EDONIQ_SFTP_PRIVATE_KEY"
    private_key_str = os.environ.get(private_key_env_var_name).replace("\\n", "\n")
    if not private_key_str:
        logger.warn(
            "Environment variable not set or empty",
            env_var=private_key_env_var_name,
            label="edoniq_import_results",
        )
        raise ValueError(
            f"Environment variable {private_key_env_var_name} not set or empty."
        )

    private_key_file = StringIO(private_key_str)
    private_key = paramiko.Ed25519Key.from_private_key(private_key_file)

    client.connect(
        hostname="217.20.192.94",
        port=20041,
        username="sftpuser",
        pkey=private_key,
    )

    return client.open_sftp(), client


class EdoniqSftpClient:
    def __enter__(self):
        (self.sftp_client, self.ssh_client) = _create_edoniq_sftp_client()
        return self.sftp_client

    def __exit__(self, exc_type, exc_value, exc_traceback):
        # self.sftp_client.close()
        self.ssh_client.close()


def load_edoniq_test_results_csv_data():
    with EdoniqSftpClient() as sftp_client:
        with sftp_client.file("/upload/PruefungResultate.csv", "r") as file:
            data = file.read().decode("utf-8")
            return data


if __name__ == "__main__":
    csv_data = load_edoniq_test_results_csv_data()
    csv_reader = csv.reader(StringIO(csv_data), delimiter=";")
    for i, row in enumerate(csv_reader):
        # if len(row) > 4 and row[4] == "AG 2023 A" and row[5] == "de_üK1_KO_Testlauf":
        #     print(row)
        if len(row) > 4 and row[6] == "1691151920116":
            print(row)
        # if i < 10:
        #     print(row)
