"""Confirm a staged master catalog intent run (registry backfill + FK linking).

CLI:
    python -m app.jobs.master_catalog_intent_confirm --run-id 1
    python -m app.jobs.master_catalog_intent_confirm --run-id 1 --dry-run
"""

from __future__ import annotations

import argparse
import logging
import sys

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


def run_confirm_intent(
    run_id: int,
    *,
    dry_run: bool = False,
    create_registry_rows: bool = False,
    link_products: bool = True,
    run_backfill: bool = False,
    allow_taxonomy_invent: bool = False,
) -> dict:
    from db.master_catalog_intent import confirm_intent_run
    from db.session import get_session

    with get_session() as session:
        result = confirm_intent_run(
            session,
            run_id,
            create_registry_rows=create_registry_rows,
            link_products=link_products,
            run_backfill=run_backfill,
            dry_run=dry_run,
            allow_taxonomy_invent=allow_taxonomy_invent,
        )
        if not dry_run:
            session.commit()
    return {"status": "ok", **result}


def main() -> int:
    parser = argparse.ArgumentParser(description="Confirm a master catalog intent preview run")
    parser.add_argument("--run-id", type=int, required=True)
    parser.add_argument("--dry-run", action="store_true")
    parser.add_argument(
        "--create-registry",
        action="store_true",
        help="Allow inventing missing registry rows (requires invent unlock)",
    )
    parser.add_argument("--no-create-registry", action="store_true", help="Deprecated; invent is off by default")
    parser.add_argument("--no-link-products", action="store_true")
    parser.add_argument("--backfill", action="store_true", help="Run registry backfill (requires invent unlock)")
    parser.add_argument("--no-backfill", action="store_true", help="Deprecated; backfill is off by default")
    parser.add_argument(
        "--allow-taxonomy-invent",
        action="store_true",
        help="Unlock taxonomy invent for this confirm (creates nodes/collections)",
    )
    args = parser.parse_args()

    invent = bool(args.allow_taxonomy_invent or args.create_registry or args.backfill)
    result = run_confirm_intent(
        args.run_id,
        dry_run=args.dry_run,
        create_registry_rows=bool(args.create_registry) and not args.no_create_registry,
        link_products=not args.no_link_products,
        run_backfill=bool(args.backfill) and not args.no_backfill,
        allow_taxonomy_invent=invent,
    )
    logger.info("Intent run %s result: %s", args.run_id, result)
    return 0 if result.get("status") == "ok" else 1


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