#!/usr/bin/env python3
"""Run the ClientFlow fiscal enrichment worker.

Typical production use:

  python scripts/enrich_fiscal_customers.py --incremental --limit 100

The worker is idempotent: it enriches/suggests fiscal customers for open
opportunities missing local_customer_id and never creates opportunities.
"""
from __future__ import annotations

import argparse
import json
import os
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

from app.fiscal_enrichment_service import enrich_open_opportunities, ensure_fiscal_enrichment_schema


def main() -> int:
    parser = argparse.ArgumentParser(description="Enriquecer oportunidades sem cliente fiscal")
    parser.add_argument("--limit", type=int, default=100, help="Máximo de oportunidades abertas a analisar")
    parser.add_argument("--no-auto-apply", action="store_true", help="Criar apenas sugestões, sem auto-associação forte")
    parser.add_argument("--daily", action="store_true", help="Marcar execução como diária/batch")
    parser.add_argument("--incremental", action="store_true", help="Marcar execução como incremental")
    args = parser.parse_args()

    ensure_fiscal_enrichment_schema()
    mode = "daily" if args.daily else "incremental"
    result = enrich_open_opportunities(limit=args.limit, apply_safe=not args.no_auto_apply, mode=mode)
    print(json.dumps(result, ensure_ascii=False, indent=2, default=str))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
