"""Backfill variation-parent attributes from unanimous child values.

Copies all non-configuration attributes shared by every child onto the parent
shell (materials, hinges, finish, construction, etc.). Skips axis/size/SEO/
media/price fields so parent titles and configurable options stay intact.

Examples:
  python -m app.jobs.impute_parent_attributes_from_children --dry-run
  python -m app.jobs.impute_parent_attributes_from_children --dry-run --sku ACH-B-PARENT
  python -m app.jobs.impute_parent_attributes_from_children --apply
  python -m app.jobs.impute_parent_attributes_from_children --apply --sku ACH-B-PARENT
"""

from __future__ import annotations

import argparse
import json
import sys
from typing import List, Optional

from db.session import get_session
from db.variation_builder import copy_shared_child_attrs_to_parents_from_relations


def main() -> int:
    parser = argparse.ArgumentParser(
        description="Copy unanimous non-configuration child attributes onto variation parents"
    )
    parser.add_argument("--sku", action="append", dest="skus", help="Limit to parent SKU(s); repeatable")
    parser.add_argument("--apply", action="store_true", help="Persist attribute copies")
    parser.add_argument("--dry-run", action="store_true", help="Preview only (default unless --apply)")
    parser.add_argument(
        "--source-label",
        default="parent_attr_impute_from_children",
        help="source_label written on master_product_attribute_value rows",
    )
    args = parser.parse_args()
    dry_run = not args.apply

    with get_session() as session:
        result = copy_shared_child_attrs_to_parents_from_relations(
            session,
            parent_skus=args.skus,
            source_label=args.source_label,
            dry_run=dry_run,
        )
        if not dry_run:
            session.commit()

    print(json.dumps(result, indent=2, default=str))
    return 0 if result.get("status") == "ok" else 1


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