# Generated by Django 4.2.23 on 2025-07-18 23:42

from decimal import Decimal

from django.db import migrations


def convert_overage(apps, schema_editor):
    """Convert 'overage' field to 'setup_quantity' and 'attrition' fields.
    
    - The 'overage' field is split into two new fields:
      - 'setup_quantity': The integer part of the overage.
      - 'attrition': The fractional part of the overage.
    """

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

    # Fetch all BomItem objects with a non-zero overage
    bom_items = BomItem.objects.exclude(overage='').exclude(overage=None).distinct()

    if bom_items.count() == 0:
        return
    
    print(f"\nConverting {bom_items.count()} BomItem objects with 'overage' to 'setup_quantity' and 'attrition'")

    for item in bom_items:

        # First attempt - convert to a percentage
        overage = str(item.overage).strip()

        if overage.endswith('%'):
            try:
                attrition = Decimal(overage[:-1])
                attrition = max(0, attrition)  # Ensure it's not negative
                attrition = min(100, attrition)  # Cap at 100%
                
                item.attrition = attrition
                item.setup_quantity = Decimal(0)
                item.save()
            except Exception as e:
                print(f" - Error converting {item.pk} from percentage: {e}")
                continue

        else:
            # If not a percentage, treat it as a decimal number
            try:
                setup_quantity = Decimal(overage)
                setup_quantity = max(0, setup_quantity)  # Ensure it's not negative
                
                item.setup_quantity = setup_quantity
                item.attrition = Decimal(0)
                item.save()
            except Exception as e:
                print(f"- Error converting {item.pk} from decimal: {e}")
                continue


def revert_overage(apps, schema_editor):
    """Revert the 'setup_quantity' and 'attrition' fields back to 'overage'.
    
    - Combines 'setup_quantity' and 'attrition' back into the 'overage' field.
    """

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

    # First, convert all 'attrition' values to percentages
    for item in BomItem.objects.exclude(attrition=0).distinct():
        item.overage = f"{item.attrition}%"
        item.save()

    # Second, convert all 'setup_quantity' values to strings
    for item in BomItem.objects.exclude(setup_quantity=0).distinct():
        item.overage = str(item.setup_quantity or 0)
        item.save()


class Migration(migrations.Migration):

    dependencies = [
        ("part", "0137_bomitem_attrition_bomitem_rounding_multiple_and_more"),
    ]

    operations = [
        migrations.RunPython(
            code=convert_overage,
            reverse_code=revert_overage,
        )
    ]
