"""Replay goods_receipt qty from purchase items where product stock was never updated."""
from collections import defaultdict

from sqlalchemy import func

from app.core.database import SessionLocal
from app.models.inventory import Product
from app.models.purchases import Purchase, PurchaseItem
from app.services.branch_inventory_guard import add_received_branch_stock
from app.services.inventory_service import InventoryService


def main() -> None:
    db = SessionLocal()
    inv = InventoryService(db)
    rows = (
        db.query(
            PurchaseItem.product_id,
            Purchase.branch_id,
            func.sum(PurchaseItem.quantity),
        )
        .join(Purchase, Purchase.id == PurchaseItem.purchase_id)
        .filter(
            PurchaseItem.product_id.isnot(None),
            PurchaseItem.is_inventory == True,  # noqa: E712
        )
        .group_by(PurchaseItem.product_id, Purchase.branch_id)
        .all()
    )
    expected: dict[str, int] = defaultdict(int)
    branch_by_product: dict[str, str] = {}
    for product_id, branch_id, total_qty in rows:
        pid = str(product_id)
        expected[pid] += int(float(total_qty or 0))
        if branch_id:
            branch_by_product[pid] = str(branch_id)

    updated = 0
    for pid, need_qty in expected.items():
        if need_qty <= 0:
            continue
        product = db.query(Product).filter(Product.id == pid).first()
        if not product:
            continue
        have = int(product.quantity or 0)
        delta = need_qty - have
        if delta <= 0:
            continue
        branch_id = branch_by_product.get(pid) or (
            str(product.branch_id) if product.branch_id else None
        )
        ok, msg = inv.update_product_quantity(
            product_id=pid,
            quantity_change=delta,
            transaction_type="goods_receipt",
            reference="Backfill from purchase history",
            branch_id=branch_id,
        )
        if ok:
            updated += 1
            print(f"OK {product.name}: +{delta} (now ~{need_qty})")
        else:
            print(f"FAIL {pid}: {msg}")

    db.commit()
    print(f"products_updated={updated}")


if __name__ == "__main__":
    main()
