"""Create/update outbound channel schema only.

Schema sync provisions the remote building blocks needed for faster downstream
catalog pushes:
- Magento categories / Shopify collections and product taxonomy targets
- Channel attributes / metafields and Magento select options
- Local registry/linkback rows for created or discovered remotes

It intentionally skips SKU assignment/publish work.

CLI:
    python -m app.jobs.channel_schema_sync
    python -m app.jobs.channel_schema_sync --apply
    python -m app.jobs.channel_schema_sync --apply --channel magento --magento-connection-id 2
"""

from __future__ import annotations

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


def run_channel_schema_sync(
    *,
    dry_run: bool = True,
    magento_connection_id: Optional[int] = None,
    shopify_connection_id: Optional[int] = None,
    only_assigned: bool = True,
    include_magento: bool = True,
    include_shopify: bool = True,
    create_missing: bool = True,
    provision_attributes: bool = True,
    include_brand_collections: bool = True,
    shopify_brand_filter: Optional[List[str]] = None,
    limit: Optional[int] = None,
    baseline_first: bool = True,
) -> Dict[str, Any]:
    from app.jobs.channel_catalog_provision import run_channel_catalog_provision

    result = run_channel_catalog_provision(
        dry_run=dry_run,
        magento_connection_id=magento_connection_id,
        shopify_connection_id=shopify_connection_id,
        only_assigned=only_assigned,
        include_magento=include_magento,
        include_shopify=include_shopify,
        create_missing=create_missing,
        assign_skus=False,
        delta_only=True,
        seed_master_listing_paths=False,
        provision_attributes=provision_attributes,
        include_brand_collections=include_brand_collections,
        shopify_brand_filter=shopify_brand_filter,
        limit=limit,
        baseline_first=baseline_first,
    )
    result["sync_mode"] = "channel_schema"
    result["schema_only"] = True
    return result


def main() -> int:
    parser = argparse.ArgumentParser(description="Create/update outbound channel schema only")
    parser.add_argument("--dry-run", dest="dry_run", action="store_true", default=True)
    parser.add_argument("--apply", dest="dry_run", action="store_false", help="Create/update remotes")
    parser.add_argument("--magento-connection-id", type=int, default=None)
    parser.add_argument("--shopify-connection-id", type=int, default=None)
    parser.add_argument(
        "--channel",
        action="append",
        choices=["magento", "shopify"],
        default=None,
        help="Limit to one channel (repeatable). Default: both when connections exist.",
    )
    parser.add_argument(
        "--all-products",
        dest="only_assigned",
        action="store_false",
        help="Use all active master SKUs, not only channel-assigned SKUs",
    )
    parser.add_argument(
        "--no-create-missing",
        dest="create_missing",
        action="store_false",
        help="Preview only; do not create missing categories/collections/attributes",
    )
    parser.add_argument(
        "--no-attributes",
        dest="provision_attributes",
        action="store_false",
        help="Skip attribute/metafield + configurable option provision",
    )
    parser.add_argument(
        "--no-brand-collections",
        dest="include_brand_collections",
        action="store_false",
        help="Skip Shopify brand-based collections",
    )
    parser.add_argument(
        "--shopify-brand",
        action="append",
        default=None,
        help="Limit Shopify collection provision to these brand names (repeatable)",
    )
    parser.add_argument("--limit", type=int, default=None)
    parser.add_argument(
        "--no-baseline-first",
        dest="baseline_first",
        action="store_false",
        help="Skip Magento baseline pull before schema sync",
    )
    args = parser.parse_args()

    channels = [str(ch).strip().lower() for ch in (args.channel or []) if str(ch).strip()]
    include_magento = not channels or "magento" in channels
    include_shopify = not channels or "shopify" in channels

    result = run_channel_schema_sync(
        dry_run=args.dry_run,
        magento_connection_id=args.magento_connection_id,
        shopify_connection_id=args.shopify_connection_id,
        only_assigned=args.only_assigned,
        include_magento=include_magento,
        include_shopify=include_shopify,
        create_missing=args.create_missing,
        provision_attributes=args.provision_attributes,
        include_brand_collections=args.include_brand_collections,
        shopify_brand_filter=args.shopify_brand,
        limit=args.limit,
        baseline_first=args.baseline_first,
    )
    print(json.dumps(result, indent=2, default=str))
    return 0


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