# Generated by Django 4.2.23 on 2025-07-22 03:03

from django.db import migrations

def cache_bom_valid(apps, schema_editor):
    """Calculate and cache the BOM validity for all parts.
    
    Procedure:

    - Find all parts which have linked BOM item(s)
    - Limit to parts which have a stored BOM checksum
    - For each such part, calculate and update the BOM "validity"
    """

    from InvenTree.tasks import offload_task
    from part.tasks import check_bom_valid

    Part = apps.get_model('part', 'Part')
    BomItem = apps.get_model('part', 'BomItem')

    # Fetch all BomItem objects
    bom_items = BomItem.objects.exclude(part=None).prefetch_related('part').distinct()

    parts_to_update = set()

    for item in bom_items:

        # Parts associated with this BomItem
        parts = []

        if item.inherited:
            # Find all inherited assemblies for this BomItem
            parts = list(
                Part.objects.filter(
                    tree_id=item.part.tree_id,
                    lft__gte=item.part.lft,
                    rght__lte=item.part.rght
                )
            )
        else:
            parts = [item.part]

        for part in parts:
            # Part has already been observed - skip
            if part in parts_to_update:
                continue

            # Part has no BOM checksum - skip
            if not part.bom_checksum:
                continue
        
            # Part has not already been validated
            if not part.bom_checked_date:
                continue

            parts_to_update.add(part)

    if len(parts_to_update) > 0:
        print(f"\nScheduling {len(parts_to_update)} parts to update BOM validity.")

    for part in parts_to_update:
        # Offload task to recalculate the BOM checksum for this part
        # The background worker will process these when the server restarts
        offload_task(
            check_bom_valid,
            part.pk,
            force_async=True,
            group='part'
        )


class Migration(migrations.Migration):

    dependencies = [
        ("part", "0140_part_bom_validated"),
    ]

    operations = [
        migrations.RunPython(cache_bom_valid, migrations.RunPython.noop),
    ]
