import structlog

from vbv_lernwelt.core.base import LoggedCommand
from vbv_lernwelt.edoniq_test.result_import.edoniq_sftp_connection import (
    load_edoniq_test_results_csv_data,
)
from vbv_lernwelt.edoniq_test.result_import.services import (
    create_edoniq_csv_test_result,
    filter_relevant_rows,
    upsert_edoniq_test_result,
)

logger = structlog.get_logger(__name__)


class Command(LoggedCommand):
    help = "Imports Test Results from Edoniq"

    def handle(self, *args, **options):
        logger.info(
            "edoniq_import_results job started",
            label="edoniq_import_results",
        )

        stat_results = {
            "num_created": 0,
            "num_updated": 0,
            "num_error": 0,
            "num_passed": 0,
            "num_failed": 0,
        }

        csv_data = load_edoniq_test_results_csv_data()
        relevant_rows = filter_relevant_rows(csv_data)
        stat_results["num_relevant_edoniq_csv_rows"] = len(relevant_rows)

        for row in relevant_rows:
            result_row = create_edoniq_csv_test_result(row)
            assignment_completion, created = upsert_edoniq_test_result(
                result_row, fail_silently=True
            )
            if assignment_completion:
                if created:
                    stat_results["num_created"] += 1
                else:
                    stat_results["num_updated"] += 1
                if assignment_completion.evaluation_passed:
                    stat_results["num_passed"] += 1
                else:
                    stat_results["num_failed"] += 1
            else:
                stat_results["num_error"] += 1

        self.job_log.json_data = stat_results
        self.job_log.save()

        logger.info(
            "edoniq_import_results job finished",
            label="edoniq_import_results",
            stat_results=stat_results,
        )
