"""Move all MCI buyer on-top demand from W22 (202622) → W23 (202623)."""
from sqlalchemy import text
from backend.models.database import SessionLocal

db = SessionLocal()
try:
    before = db.execute(text("""
        SELECT COUNT(*) AS n, SUM(quantity)::float AS qty
        FROM on_top_inputs WHERE buyer='MCI' AND year_week=202622
    """)).mappings().first()
    print(f"Before:  W22 rows={before['n']}  qty={before['qty']:,.0f}")

    after_existing = db.execute(text("""
        SELECT COUNT(*) AS n FROM on_top_inputs
        WHERE buyer='MCI' AND year_week=202623
    """)).scalar()
    print(f"         W23 already has {after_existing} MCI rows")

    res = db.execute(text("""
        UPDATE on_top_inputs
        SET year_week = 202623
        WHERE buyer = 'MCI' AND year_week = 202622
    """))
    db.commit()
    print(f"Updated: {res.rowcount} rows")

    after = db.execute(text("""
        SELECT year_week, COUNT(*) AS n, SUM(quantity)::float AS qty
        FROM on_top_inputs WHERE buyer='MCI'
        GROUP BY year_week ORDER BY year_week
    """)).mappings().all()
    print("After:")
    for r in after:
        print(f"  yw={r['year_week']}  rows={r['n']}  qty={r['qty']:,.0f}")
finally:
    db.close()
