"""Remove collection/lifestyle images attached to RTA-* SKUs.

Examples:
  python -m app.jobs.cleanup_rta_collection_images
  python -m app.jobs.cleanup_rta_collection_images --apply
"""

from __future__ import annotations

import argparse
import json
from typing import Any, Dict, Optional, Sequence


def cleanup_rta_collection_images(*, apply: bool = False, sample_limit: int = 50) -> Dict[str, Any]:
    from sqlalchemy import select

    from db.master_product_images import COLLECTION_IMAGE_ROLES, normalize_image_role
    from db.models import MasterProductImage
    from db.session import get_session
    from db.tribeca_sku_parse import collection_asset_key

    with get_session() as session:
        rows = list(
            session.scalars(
                select(MasterProductImage).where(MasterProductImage.sku.ilike("RTA-%"))
            ).all()
        )
        victims = []
        for row in rows:
            role = normalize_image_role(getattr(row, "image_role", None))
            if role in COLLECTION_IMAGE_ROLES or collection_asset_key(str(row.file_name or "")):
                victims.append(row)
        sample = [
            {
                "id": int(row.id),
                "sku": row.sku,
                "file_name": row.file_name,
                "image_role": normalize_image_role(getattr(row, "image_role", None)),
            }
            for row in victims[:sample_limit]
        ]
        if apply and victims:
            for row in victims:
                session.delete(row)
            session.commit()
        else:
            session.rollback()
    return {
        "status": "ok",
        "applied": bool(apply),
        "deleted_count": len(victims) if apply else 0,
        "would_delete_count": len(victims),
        "sample": sample,
    }


def main(argv: Optional[Sequence[str]] = None) -> int:
    parser = argparse.ArgumentParser(description="Remove collection-role images from RTA SKUs")
    parser.add_argument("--apply", action="store_true", help="Delete rows; default is dry-run")
    parser.add_argument("--sample-limit", type=int, default=50)
    args = parser.parse_args(list(argv) if argv is not None else None)
    print(json.dumps(cleanup_rta_collection_images(apply=args.apply, sample_limit=args.sample_limit), indent=2))
    return 0


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