"""One-time/local master-product taxonomy reconciliation.

Dry-run is the default. Use --apply only after reviewing the JSON summary.
Remote Magento/Shopify membership is reconciled on the next product push.
"""

from __future__ import annotations

import argparse
import json

from sqlalchemy import select

from db.master_taxonomy_sync import link_products_to_taxonomy_from_master
from db.models import MagentoConnection, ShopifyConnection
from db.session import get_session


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--apply", action="store_true", help="Persist the reconciliation")
    parser.add_argument("--sku", action="append", dest="skus", help="Limit to a SKU; repeatable")
    parser.add_argument("--limit", type=int)
    args = parser.parse_args()

    with get_session() as session:
        magento_id = session.scalar(
            select(MagentoConnection.id)
            .where(MagentoConnection.status == "active")
            .order_by(MagentoConnection.id)
            .limit(1)
        )
        shopify_id = session.scalar(
            select(ShopifyConnection.id)
            .where(ShopifyConnection.status == "active")
            .order_by(ShopifyConnection.id)
            .limit(1)
        )
        result = link_products_to_taxonomy_from_master(
            session,
            skus=args.skus,
            replace_existing=True,
            sync_channels=True,
            magento_connection_id=int(magento_id) if magento_id else None,
            shopify_connection_id=int(shopify_id) if shopify_id else None,
            dry_run=not args.apply,
            limit=args.limit,
        )
        if args.apply:
            session.commit()
        print(json.dumps(result, indent=2, default=str))


if __name__ == "__main__":
    main()
