#!/usr/bin/env python3
"""Inspect Jasmin document candidates for an opportunity.

Optionally sync recent Jasmin documents first, then prints open/valid candidates first
and ignored closed/completed/cancelled documents afterwards.
"""
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("--limit", type=int, default=20)
    parser.add_argument("--sync", action="store_true", help="Sync recent Jasmin reconciliation candidates before inspection")
    parser.add_argument("--days", type=int, default=30)
    args = parser.parse_args()

    if args.sync:
        from app.external_reconciliation_sync import sync_jasmin_reconciliation_candidates
        sync_result = await sync_jasmin_reconciliation_candidates(limit=100, days=args.days)
        print(json.dumps({"sync_jasmin": sync_result}, ensure_ascii=False, indent=2, default=_json_default))

    from app.jasmin_backfill_service import find_jasmin_document_candidates_for_opportunity
    candidates = find_jasmin_document_candidates_for_opportunity(args.opportunity_id, limit=args.limit)
    print(json.dumps({"opportunity_id": args.opportunity_id, "candidates": candidates}, ensure_ascii=False, indent=2, default=_json_default))
    return 0


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