#!/usr/bin/env python3
"""Replace imported Jasmin quotation/proforma details for an opportunity.

Use this when an old/closed quotation was linked by mistake and a newer open
reconciliation item should become the active document for the opportunity.
This deletes only ClientFlow imported Jasmin quotation/proforma artifacts; it does
not delete documents in Jasmin.
"""
from __future__ import annotations

import argparse
import asyncio
import json
from decimal import Decimal
from typing import Any


def _json_default(value: Any) -> str:
    if isinstance(value, Decimal):
        return str(value)
    return str(value)


async def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--opportunity-id", required=True)
    parser.add_argument("--item-id", required=True, help="reconciliation_items.id for the open/valid Jasmin candidate")
    parser.add_argument("--dry-run", action="store_true")
    args = parser.parse_args()

    from app.jasmin_backfill_service import replace_jasmin_document_for_opportunity_async

    result = await replace_jasmin_document_for_opportunity_async(
        opportunity_id=args.opportunity_id,
        item_id=args.item_id,
        actor="operator_cli_replace_jasmin_document",
        dry_run=args.dry_run,
    )
    print(json.dumps(result, ensure_ascii=False, indent=2, default=_json_default))
    return 0 if result.get("ok") else 2


if __name__ == "__main__":
    raise SystemExit(asyncio.run(main()))
