"""Prune non-preferred image rows for one or more master SKUs.

Examples:
  python -m app.jobs.prune_master_product_images --sku ACH-TOUCH UP KIT --dry-run
  python -m app.jobs.prune_master_product_images --sku ACH-TOUCH UP KIT --sku PB-CH-TOUCH UP KIT --apply
  python -m app.jobs.prune_master_product_images --all-active --apply
"""

from __future__ import annotations

import argparse
import json
from typing import Optional, Sequence


def main(argv: Optional[Sequence[str]] = None) -> int:
    from db.master_product_images import prune_nonpreferred_product_image_rows
    from db.models import MasterProduct
    from db.session import get_session
    from sqlalchemy import select

    parser = argparse.ArgumentParser(description="Prune non-preferred image rows for specific master SKUs")
    parser.add_argument("--sku", action="append", default=[], help="Master SKU to prune; repeatable")
    parser.add_argument(
        "--all-active",
        action="store_true",
        help="Prune all active master SKUs (removes sample_door rows from non-sample-door SKUs only)",
    )
    mode = parser.add_mutually_exclusive_group(required=True)
    mode.add_argument("--dry-run", action="store_true", help="Report rows that would be deleted")
    mode.add_argument("--apply", action="store_true", help="Delete non-preferred rows")
    args = parser.parse_args(list(argv) if argv is not None else None)

    if not args.sku and not args.all_active:
        parser.error("Pass at least one --sku or use --all-active")

    target_skus = list(args.sku or [])

    with get_session() as session:
        if args.all_active:
            target_skus = [
                str(sku or "").strip().upper()
                for sku in session.scalars(
                    select(MasterProduct.sku)
                    .where(MasterProduct.is_active.is_(True))
                    .order_by(MasterProduct.sku.asc())
                ).all()
                if str(sku or "").strip()
            ]
        result = prune_nonpreferred_product_image_rows(
            session,
            target_skus,
            dry_run=bool(args.dry_run),
        )
        if args.apply:
            session.commit()
        else:
            session.rollback()
    print(json.dumps(result, indent=2))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
