"""One-off: sync branch allocations from product.quantity (run on server)."""
from app.core.database import SessionLocal
from app.models.inventory import Product
from app.models.inventory_allocation import BranchInventoryAllocation
from app.services.branch_inventory_guard import add_received_branch_stock


def main() -> None:
    db = SessionLocal()
    updated = 0
    try:
        for product in db.query(Product).filter(
            Product.active == True, Product.quantity > 0
        ).all():
            if not product.branch_id:
                continue
            pid, bid = str(product.id), str(product.branch_id)
            qty = int(product.quantity or 0)
            if qty <= 0:
                continue
            existing = (
                db.query(BranchInventoryAllocation)
                .filter(
                    BranchInventoryAllocation.product_id == pid,
                    BranchInventoryAllocation.branch_id == bid,
                    BranchInventoryAllocation.allocation_status == "received",
                )
                .first()
            )
            if existing and int(existing.available_quantity or 0) >= qty:
                continue
            if existing:
                existing.available_quantity = qty
                existing.received_quantity = max(
                    int(existing.received_quantity or 0), qty
                )
                updated += 1
            else:
                add_received_branch_stock(
                    db, pid, bid, qty, cost_per_unit=float(product.cost_price or 0)
                )
                updated += 1
        db.commit()
        print(f"backfill_updated={updated}")
    finally:
        db.close()


if __name__ == "__main__":
    main()
