#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import django

# Setup Django
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'myproject'))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
django.setup()

from inventory.models import Reservation
from django.db.models import Count

# Найти дубликаты резервов трансформаций
duplicates = Reservation.objects.filter(
    transformation_input__isnull=False
).values(
    'transformation_input', 'product', 'warehouse'
).annotate(
    count=Count('id')
).filter(
    count__gt=1
)

print(f"Found {duplicates.count()} duplicate transformation reservations")

if duplicates.exists():
    print("\nDuplicate groups:")
    for dup in duplicates[:10]:
        print(f"  TransformationInput ID: {dup['transformation_input']}, "
              f"Product ID: {dup['product']}, "
              f"Warehouse ID: {dup['warehouse']}, "
              f"Count: {dup['count']}")

        # Show actual reservations
        reservations = Reservation.objects.filter(
            transformation_input_id=dup['transformation_input'],
            product_id=dup['product'],
            warehouse_id=dup['warehouse']
        )
        for res in reservations:
            print(f"    - Reservation ID {res.id}: quantity={res.quantity}, status={res.status}")

    print("\n--- CLEANING DUPLICATES ---")

    # Для каждой группы дубликатов оставляем только один резерв
    for dup in duplicates:
        reservations = Reservation.objects.filter(
            transformation_input_id=dup['transformation_input'],
            product_id=dup['product'],
            warehouse_id=dup['warehouse']
        ).order_by('id')

        # Оставляем первый, удаляем остальные
        first = reservations.first()
        others = reservations.exclude(id=first.id)
        count = others.count()

        if count > 0:
            others.delete()
            print(f"Deleted {count} duplicate reservations for TransformationInput {dup['transformation_input']}")

    print("\n--- DONE ---")
else:
    print("No duplicates found!")
