#!/usr/bin/env python3
"""Run the recommended ClientFlow pipeline: enrichment -> external sync.

This orchestrator is safe to run periodically. It does not apply low-confidence
reconciliation decisions; it prepares fiscal identities first and then rebuilds
external candidates for the operator.
"""
from __future__ import annotations

import argparse
import asyncio
import json
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
from app.external_reconciliation_sync import sync_all_external_reconciliation_candidates


async def _run(args: argparse.Namespace) -> dict:
    ensure_fiscal_enrichment_schema()
    enrichment = enrich_open_opportunities(
        limit=args.enrichment_limit,
        apply_safe=not args.no_auto_apply,
        mode="pipeline",
    )
    reconciliation = await sync_all_external_reconciliation_candidates(limit=args.limit, days=args.days)
    return {"enrichment": enrichment, "reconciliation": reconciliation}


def main() -> int:
    parser = argparse.ArgumentParser(description="Correr pipeline ClientFlow: enriquecimento fiscal + reconciliação")
    parser.add_argument("--days", type=int, default=7, help="Janela de reconciliação externa")
    parser.add_argument("--limit", type=int, default=100, help="Limite por fonte externa")
    parser.add_argument("--enrichment-limit", type=int, default=100, help="Limite de oportunidades a enriquecer antes da reconciliação")
    parser.add_argument("--no-auto-apply", action="store_true", help="Não auto-associar sugestões fiscais fortes")
    args = parser.parse_args()
    result = asyncio.run(_run(args))
    print(json.dumps(result, ensure_ascii=False, indent=2, default=str))
    return 0


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