# Generated by Django 5.1 on 2024-09-09 20:35
from pathlib import Path

import pandas as pd
from django.apps import apps as django_apps
from django.conf import settings
from django.db import migrations
from edc_utils import get_utcnow
from tqdm import tqdm


def populate_substitutions(apps, schema_editor):
    """import CSV file into pandas dataframe and use DF to
    populate the model.

    CSV file was sent to ERIK on 2024-09-09 in relation to
    a possible protocol violation where a subject was given the
    incorrect IMP. The CSV file lists `sid` where a bottle was not ready
    to dispense and a bottle of `dispensed_sid` was dispensed instead.
    """
    path = Path(settings.META_PHARMACY_RX_SUBSTITUTION_FILE).expanduser()
    df = pd.read_csv(path, header=1)
    df = df.rename(
        columns={"MISSING DRUG": "sid", "SUBSTITUTE": "dispensed_sid", "SITE": "site_id"}
    )
    df = df.rename(
        columns={"MISSING DRUG": "sid", "SUBSTITUTE": "dispensed_sid", "SITE": "site_id"}
    )
    df["sid"] = df["sid"].apply(pd.to_numeric, errors="coerce")
    df["dispensed_sid"] = df["dispensed_sid"].apply(pd.to_numeric, errors="coerce")
    df["site_id"] = df["site_id"].apply(pd.to_numeric, errors="coerce")
    now = get_utcnow()
    model_cls = django_apps.get_model("meta_pharmacy.substitutions")
    df_error = df[df["dispensed_sid"].isna()]
    df_error = df_error.reset_index()
    df_ok = df[df["dispensed_sid"].notna()]
    df_ok = df_ok.reset_index()
    data = [
        model_cls(
            row_index=row["index"],
            report_datetime=now,
            site_id=row["site_id"],
            sid=row["sid"],
            dispensed_sid=row["dispensed_sid"],
            user_created="erikvw",
            created=now,
            locale_created="en-gb",
        )
        for _, row in df_ok.iterrows()
    ]
    created = len(model_cls.objects.bulk_create(data))
    for obj in tqdm(model_cls.objects.all(), total=created):
        obj.save()
    if not df_error.empty:
        print(df_error[["index", "sid"]])


class Migration(migrations.Migration):

    dependencies = [
        ("meta_pharmacy", "0002_initial"),
    ]

    operations = [migrations.RunPython(populate_substitutions)]
