"""Backfill filter attributes for collections that have no peer donors.

Uses observed full-collection profiles, collection-name color/finish derivation,
and series-peer propagation (Anna/Maya/…). Optionally stores the resolved
profile on ``master_collection_registry.aliases.filter_attributes``.

Examples:
    python -m app.jobs.backfill_collection_filter_attributes --dry-run
    python -m app.jobs.backfill_collection_filter_attributes --attribute color --attribute door_style
    python -m app.jobs.backfill_collection_filter_attributes --apply
    python -m app.jobs.backfill_collection_filter_attributes --apply --no-update-registry
"""

from __future__ import annotations

import argparse
import json
import sys

from db.collection_filter_backfill import backfill_collection_filter_attributes
from db.session import get_session


def main() -> int:
    parser = argparse.ArgumentParser(
        description="Backfill empty-collection filter attributes from series peers / collection name"
    )
    parser.add_argument("--attribute", action="append", default=None, help="Attribute code; repeatable")
    parser.add_argument("--source-label", default="collection_filter_backfill")
    parser.add_argument(
        "--no-update-registry",
        action="store_true",
        help="Do not write resolved profiles onto master_collection_registry.aliases",
    )
    parser.add_argument("--apply", action="store_true", help="Write suggested values")
    parser.add_argument("--dry-run", action="store_true", help="Preview only; default unless --apply")
    args = parser.parse_args()

    dry_run = not args.apply
    with get_session() as session:
        result = backfill_collection_filter_attributes(
            session,
            attributes=args.attribute,
            source_label=args.source_label,
            update_registry=not args.no_update_registry,
            dry_run=dry_run,
        )
        if not dry_run:
            session.commit()
    print(json.dumps(result, indent=2, default=str))
    return 0


if __name__ == "__main__":
    sys.exit(main())
