from django.db import migrations


def normalize_value(value):
    return (value or "").strip().lower()


MANUAL_CROP_FIXES = {
    # result_id: crop translation name to search
    348: "Corn",
    405: "Triticale",
    554: "Maiz",
    697: "Universal Green Coffee",
    751: "Universal Green Coffee",
}


def forwards(apps, schema_editor):
    Result = apps.get_model("results", "Result")
    CropTranslation = apps.get_model("cropmanagement", "CropTranslation")

    updated = 0
    not_found = []

    for result_id, crop_name in MANUAL_CROP_FIXES.items():
        result = Result.objects.filter(id=result_id).first()

        if not result:
            not_found.append(f"Result {result_id}: result not found")
            continue

        if result.crop_id:
            continue

        device = getattr(result, "device", None)
        language_id = getattr(device, "language_id_id", None)

        if not language_id:
            not_found.append(f"Result {result_id}: device language missing")
            continue

        crop_translation = (
            CropTranslation.objects
            .filter(name__iexact=crop_name)
            .first()
        )
        result.crop_id = crop_translation.crop_id
        result.save(update_fields=["crop"])
        updated += 1

    print("Missing result crop fix summary")
    print(f"Updated: {updated}")
    print(f"Not found: {len(not_found)}")

    for item in not_found:
        print(item)


def backwards(apps, schema_editor):
    Result = apps.get_model("results", "Result")

    Result.objects.filter(
        id__in=MANUAL_CROP_FIXES.keys()
    ).update(crop_id=None)


class Migration(migrations.Migration):

    dependencies = [
        ("results", "0019_auto_20260426_1820"),
    ]

    operations = [
        migrations.RunPython(forwards, backwards),
    ]
