statement-fetch 0.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
statement_fetch/cli.py ADDED
@@ -0,0 +1,686 @@
1
+ """Pure public CLI entrypoint and subcommand dispatcher for `statement-fetch`."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import asyncio
6
+ import json
7
+ import os
8
+ import shutil
9
+ import sys
10
+ import tempfile
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ from . import api
15
+ from ._playwright import check_playwright_available
16
+ from ._validators import inspect_generic_file
17
+ from .providers.example_bank import ExampleBankProvider
18
+ from .sinks.directory import DirectorySink
19
+
20
+ _CLI_SCHEMA_VERSION = 1
21
+ _PLUGIN_REGISTRY: api.PluginRegistry | None = None
22
+
23
+
24
+ def _emit_json(payload: dict[str, Any]) -> None:
25
+ print(json.dumps(payload, default=str, indent=2, ensure_ascii=False), flush=True)
26
+
27
+
28
+ def _emit_error(
29
+ command: str,
30
+ message: str,
31
+ *,
32
+ json_output: bool,
33
+ exit_code: int = api.EXIT_ERROR,
34
+ status: str = "error",
35
+ extra: dict[str, Any] | None = None,
36
+ ) -> int:
37
+ if json_output:
38
+ payload: dict[str, Any] = {
39
+ "schema_version": _CLI_SCHEMA_VERSION,
40
+ "command": command,
41
+ "ok": False,
42
+ "status": status,
43
+ "exit_code": exit_code,
44
+ "error": message,
45
+ }
46
+ if extra:
47
+ payload.update(extra)
48
+ _emit_json(payload)
49
+ else:
50
+ print(f"ERROR: {message}", file=sys.stderr)
51
+ return exit_code
52
+
53
+
54
+ def get_plugin_registry() -> api.PluginRegistry:
55
+ """Return the shared lazy plugin registry (built-ins + installed entry points)."""
56
+ global _PLUGIN_REGISTRY
57
+ if _PLUGIN_REGISTRY is None:
58
+ reg = api.PluginRegistry()
59
+ reg.register_provider(ExampleBankProvider())
60
+ reg.register_sink(DirectorySink())
61
+ reg.discover_entry_points()
62
+ _PLUGIN_REGISTRY = reg
63
+ return _PLUGIN_REGISTRY
64
+
65
+
66
+ def _parse_opt_pairs(pairs: list[str], spec: api.ProviderSpec) -> dict[str, Any]:
67
+ return api.parse_provider_options(pairs, spec)
68
+
69
+
70
+ def _parse_sink_opts(args: argparse.Namespace) -> dict[str, str]:
71
+ cfg: dict[str, str] = {}
72
+ for raw in getattr(args, "sink_opt", ()) or ():
73
+ if "=" not in raw:
74
+ raise ValueError(f"Invalid --sink-opt {raw!r}; expected KEY=VALUE.")
75
+ k, v = raw.split("=", 1)
76
+ cfg[k.strip()] = v
77
+ sink_dir = getattr(args, "sink_dir", None)
78
+ if sink_dir is not None and "dir" not in cfg:
79
+ cfg["dir"] = str(sink_dir)
80
+ return cfg
81
+
82
+
83
+ def run_doctor(*, json_output: bool = False) -> int:
84
+ checks: dict[str, dict[str, Any]] = {}
85
+ ok = True
86
+ try:
87
+ reg = get_plugin_registry()
88
+ checks["plugins"] = {
89
+ "ok": True,
90
+ "providers": reg.list_provider_ids(),
91
+ "sinks": reg.list_sink_ids(),
92
+ }
93
+ except Exception as exc:
94
+ checks["plugins"] = {"ok": False, "error": str(exc)}
95
+ ok = False
96
+
97
+ pw_check = check_playwright_available()
98
+ checks["playwright"] = pw_check
99
+ if not pw_check.get("ok"):
100
+ ok = False
101
+
102
+ rc = api.EXIT_OK if ok else api.EXIT_ERROR
103
+ if json_output:
104
+ _emit_json({
105
+ "schema_version": _CLI_SCHEMA_VERSION,
106
+ "command": "doctor",
107
+ "ok": ok,
108
+ "status": "ok" if ok else "failed",
109
+ "exit_code": rc,
110
+ "checks": checks,
111
+ })
112
+ else:
113
+ for name, info in checks.items():
114
+ mark = "OK" if info.get("ok") else "FAIL"
115
+ detail = info.get("executable") or info.get("package") or info.get("error") or "ok"
116
+ print(f"[{mark}] {name}: {detail}")
117
+ return rc
118
+
119
+
120
+ def run_inspect(paths: list[Path], *, json_output: bool = False) -> int:
121
+ ok = True
122
+ results: list[dict[str, Any]] = []
123
+ for path in paths:
124
+ if not path.is_file():
125
+ ok = False
126
+ results.append({"path": str(path), "name": path.name, "valid": False, "error": "file not found"})
127
+ if not json_output:
128
+ print(f"ERROR: file not found: {path}", file=sys.stderr)
129
+ continue
130
+ res = inspect_generic_file(path)
131
+ if not res.valid:
132
+ ok = False
133
+ results.append({
134
+ "path": str(path),
135
+ "name": path.name,
136
+ "kind": res.kind,
137
+ "valid": res.valid,
138
+ "rows": res.rows,
139
+ "error": res.error,
140
+ "bytes": path.stat().st_size,
141
+ "sha256_12": api.sha256_file(path)[:12],
142
+ })
143
+ if not json_output:
144
+ print(res.summary)
145
+ rc = api.EXIT_OK if ok else api.EXIT_ERROR
146
+ if json_output:
147
+ _emit_json({
148
+ "schema_version": _CLI_SCHEMA_VERSION,
149
+ "command": "inspect",
150
+ "ok": ok,
151
+ "status": "ok" if ok else "invalid",
152
+ "exit_code": rc,
153
+ "files": results,
154
+ })
155
+ return rc
156
+
157
+
158
+ def run_providers(*, json_output: bool = False) -> int:
159
+ try:
160
+ reg = get_plugin_registry()
161
+ all_ids = reg.list_provider_ids()
162
+ except Exception as exc:
163
+ return _emit_error("providers", str(exc), json_output=json_output, exit_code=api.EXIT_ERROR)
164
+
165
+ entries: list[dict[str, Any]] = []
166
+ errors: list[dict[str, str]] = []
167
+ for pid in all_ids:
168
+ try:
169
+ prov = reg.get_provider(pid)
170
+ entries.append(prov.spec.to_dict())
171
+ except Exception as exc:
172
+ err_msg = str(exc) or exc.__class__.__name__
173
+ errors.append({"id": pid, "error": err_msg})
174
+ entries.append({
175
+ "id": pid,
176
+ "display_name": pid,
177
+ "login_url": "",
178
+ "allowed_hosts": [],
179
+ "artifacts": [],
180
+ "options": [],
181
+ "supports_accounts": False,
182
+ "error": err_msg,
183
+ })
184
+ ok = not errors
185
+ rc = api.EXIT_OK if ok else api.EXIT_ERROR
186
+ if json_output:
187
+ payload: dict[str, Any] = {
188
+ "schema_version": _CLI_SCHEMA_VERSION,
189
+ "command": "providers",
190
+ "ok": ok,
191
+ "status": "ok" if ok else "error",
192
+ "exit_code": rc,
193
+ "providers": entries,
194
+ }
195
+ if errors:
196
+ payload["errors"] = errors
197
+ _emit_json(payload)
198
+ else:
199
+ for e in entries:
200
+ if e.get("error"):
201
+ print(f"{e['id']:<14} ERROR: {e['error']}", file=sys.stderr)
202
+ else:
203
+ arts = ",".join(a["id"] for a in e.get("artifacts", [])) or "-"
204
+ print(f"{e['id']:<14} artifacts={arts:<15} {e['login_url']}")
205
+ return rc
206
+
207
+
208
+ def _run_fetch(args: argparse.Namespace) -> int:
209
+ try:
210
+ reg = get_plugin_registry()
211
+ provider = reg.get_provider(args.provider)
212
+ except ValueError as exc:
213
+ return _emit_error(
214
+ "fetch", str(exc), json_output=args.json_output, exit_code=api.EXIT_USAGE, status="usage_error", extra={"provider": args.provider}
215
+ )
216
+ except Exception as exc:
217
+ return _emit_error("fetch", str(exc), json_output=args.json_output, exit_code=api.EXIT_ERROR, extra={"provider": args.provider})
218
+
219
+ spec = provider.spec
220
+ want_upload = bool(args.upload or args.dry_run_upload)
221
+
222
+ try:
223
+ if args.skip_existing and args.output_dir is None:
224
+ raise ValueError("--skip-existing requires --output-dir.")
225
+ if not want_upload and (args.sink_dir is not None or args.sink_opt):
226
+ raise ValueError("--sink-dir / --sink-opt require --upload or --dry-run-upload.")
227
+ start_d, end_d, explicit = api.resolve_date_range(
228
+ month_str=args.month,
229
+ date_from_str=args.date_from,
230
+ date_to_str=args.date_to,
231
+ )
232
+ opts = _parse_opt_pairs(args.opt, spec)
233
+ raw_arts_list = [a.strip() for a in (args.artifacts or "").split(",") if a.strip()]
234
+ raw_arts = tuple(raw_arts_list) or spec.default_artifact_ids()
235
+ resolved_arts = spec.resolve_artifacts(raw_arts)
236
+ raw_accts = tuple(a.strip() for a in (args.accounts or "").split(",") if a.strip() and a.strip() != "all")
237
+ req = api.FetchRequest(
238
+ period_start=start_d,
239
+ period_end=end_d,
240
+ explicit_range=explicit,
241
+ artifacts=resolved_arts,
242
+ accounts=raw_accts,
243
+ options=opts,
244
+ login_timeout_s=float(args.login_timeout),
245
+ skip_existing=bool(args.skip_existing),
246
+ )
247
+ resolved_arts = api.validate_fetch_request(provider, req)
248
+ login_url, allowed_hosts = api.resolve_provider_target(provider, req)
249
+
250
+ resolved_sink_obj: api.Sink | None = None
251
+ sink_cfg: dict[str, str] = {}
252
+ if want_upload:
253
+ raw_sink = (args.sink or "auto").strip().lower()
254
+ sink_id = "dir" if raw_sink == "auto" else raw_sink
255
+ resolved_sink_obj = reg.get_sink(sink_id)
256
+ sink_cfg = _parse_sink_opts(args)
257
+ resolved_sink_obj.validate_config(sink_cfg)
258
+ except ValueError as exc:
259
+ return _emit_error(
260
+ "fetch", str(exc), json_output=args.json_output, exit_code=api.EXIT_USAGE, status="usage_error", extra={"provider": spec.id}
261
+ )
262
+ except Exception as exc:
263
+ return _emit_error("fetch", str(exc), json_output=args.json_output, exit_code=api.EXIT_ERROR, extra={"provider": spec.id})
264
+
265
+ if args.dry_run:
266
+ plan: dict[str, Any] = {
267
+ "schema_version": _CLI_SCHEMA_VERSION,
268
+ "command": "fetch",
269
+ "provider": spec.id,
270
+ "ok": True,
271
+ "status": "dry_run",
272
+ "exit_code": api.EXIT_OK,
273
+ "login_url": login_url,
274
+ "allowed_hosts": list(allowed_hosts),
275
+ "period_start": start_d.isoformat(),
276
+ "period_end": end_d.isoformat(),
277
+ "artifacts": list(resolved_arts),
278
+ "accounts": list(raw_accts),
279
+ "options": opts,
280
+ }
281
+ if resolved_sink_obj is not None:
282
+ plan["sink"] = resolved_sink_obj.id
283
+ if args.json_output:
284
+ _emit_json(plan)
285
+ else:
286
+ print(f"[dry-run] {spec.id} ({spec.display_name}) -> {login_url}")
287
+ print(f" period={start_d.isoformat()}..{end_d.isoformat()} artifacts={','.join(resolved_arts)}")
288
+ return api.EXIT_OK
289
+
290
+ host: api.Host = api.PlaywrightHost()
291
+ auto_stage = args.output_dir is None
292
+ effective_stage_dir: Path
293
+ if args.output_dir is not None:
294
+ effective_stage_dir = args.output_dir
295
+ else:
296
+ raw_stage = Path(tempfile.mkdtemp(prefix=f"sf-{spec.id}-"))
297
+ os.chmod(raw_stage, 0o700)
298
+ effective_stage_dir = raw_stage.resolve()
299
+
300
+ def _on_stage(name: str) -> None:
301
+ if not args.quiet and not args.json_output:
302
+ print(f"[{spec.id}] stage={name}", file=sys.stderr, flush=True)
303
+
304
+ try:
305
+ result = asyncio.run(
306
+ api.run_async_fetch(
307
+ provider,
308
+ host,
309
+ req,
310
+ stage_dir=effective_stage_dir,
311
+ on_stage=_on_stage,
312
+ )
313
+ )
314
+ except ValueError as exc:
315
+ if auto_stage:
316
+ shutil.rmtree(effective_stage_dir, ignore_errors=True)
317
+ return _emit_error(
318
+ "fetch", str(exc), json_output=args.json_output, exit_code=api.EXIT_USAGE, status="usage_error", extra={"provider": spec.id}
319
+ )
320
+ except (KeyboardInterrupt, asyncio.CancelledError):
321
+ kept_stage: str | None = str(effective_stage_dir)
322
+ if auto_stage and not any(effective_stage_dir.iterdir()):
323
+ shutil.rmtree(effective_stage_dir, ignore_errors=True)
324
+ kept_stage = None
325
+ return _emit_error(
326
+ "fetch",
327
+ "Interrupted by user.",
328
+ json_output=args.json_output,
329
+ exit_code=130,
330
+ status="cancelled",
331
+ extra={
332
+ "provider": spec.id,
333
+ "stage_dir": kept_stage,
334
+ },
335
+ )
336
+
337
+ # Clean up empty auto-allocated stage dirs when nothing was staged and no manifest was kept.
338
+ stage_cleaned = False
339
+ if auto_stage and result.status in ("login_timeout", "error") and not result.artifacts:
340
+ shutil.rmtree(effective_stage_dir, ignore_errors=True)
341
+ stage_cleaned = not effective_stage_dir.exists()
342
+
343
+ sink_payload: dict[str, Any] | None = None
344
+ sink_rc = api.EXIT_OK
345
+ is_dry_run_upload = bool(args.dry_run_upload)
346
+ has_valid_artifacts = any(a.valid for a in result.artifacts)
347
+ if resolved_sink_obj is not None and result.status in ("ok", "partial") and has_valid_artifacts and result.manifest_path is not None:
348
+ try:
349
+ sres = resolved_sink_obj.deliver(
350
+ result.manifest_path,
351
+ config=sink_cfg,
352
+ dry_run=is_dry_run_upload,
353
+ )
354
+ sink_payload = sres.to_dict()
355
+ if not sres.ok:
356
+ sink_rc = api.EXIT_ERROR
357
+ elif auto_stage and not is_dry_run_upload and result.status == "ok" and result.stage_dir and result.stage_dir.exists():
358
+ shutil.rmtree(result.stage_dir, ignore_errors=True)
359
+ stage_cleaned = not result.stage_dir.exists()
360
+ except Exception as exc:
361
+ sink_rc = api.EXIT_ERROR
362
+ sink_payload = {
363
+ "sink": resolved_sink_obj.id,
364
+ "ok": False,
365
+ "status": "error",
366
+ "error": str(exc),
367
+ }
368
+ elif resolved_sink_obj is not None and auto_stage and not is_dry_run_upload and result.status == "empty" and result.stage_dir and result.stage_dir.exists():
369
+ shutil.rmtree(result.stage_dir, ignore_errors=True)
370
+ stage_cleaned = not result.stage_dir.exists()
371
+
372
+ rc_map = {
373
+ "ok": api.EXIT_OK,
374
+ "empty": api.EXIT_OK,
375
+ "partial": api.EXIT_PARTIAL,
376
+ "login_timeout": api.EXIT_LOGIN_TIMEOUT,
377
+ "error": api.EXIT_ERROR,
378
+ }
379
+ rc = sink_rc if sink_rc != api.EXIT_OK else rc_map.get(result.status, api.EXIT_ERROR)
380
+ reported_stage = None if stage_cleaned else (str(result.stage_dir) if result.stage_dir else None)
381
+ payload: dict[str, Any] = {
382
+ "schema_version": _CLI_SCHEMA_VERSION,
383
+ "command": "fetch",
384
+ "provider": spec.id,
385
+ "ok": rc == api.EXIT_OK,
386
+ "status": result.status,
387
+ "exit_code": rc,
388
+ "stage_dir": reported_stage,
389
+ "stage_dir_cleaned": stage_cleaned,
390
+ "manifest": None if stage_cleaned else (str(result.manifest_path) if result.manifest_path else None),
391
+ "files": [a.to_manifest_dict() for a in result.artifacts],
392
+ "skipped": list(result.skipped),
393
+ "errors": list(result.errors),
394
+ "timings_s": result.timings_s,
395
+ }
396
+ if sink_payload is not None:
397
+ payload["sink"] = sink_payload
398
+
399
+ if args.json_output:
400
+ _emit_json(payload)
401
+ elif not args.quiet:
402
+ print(f"[{spec.id}] status={result.status} files={len(result.artifacts)} stage={reported_stage}")
403
+ for err in result.errors:
404
+ print(f" ERROR: {err}", file=sys.stderr)
405
+ if sink_payload is not None:
406
+ sink_id_lbl = sink_payload.get("sink", "sink")
407
+ if "error" in sink_payload:
408
+ print(f"[{sink_id_lbl}] ok=False error={sink_payload['error']}", file=sys.stderr)
409
+ else:
410
+ dest_detail = (sink_payload.get("details") or {}).get("dest_dir")
411
+ dest_suffix = f" dest={dest_detail}" if dest_detail else ""
412
+ print(
413
+ f"[{sink_id_lbl}] ok={sink_payload['ok']} delivered={len(sink_payload.get('delivered', ()))} "
414
+ f"skipped={len(sink_payload.get('skipped', ()))} failed={len(sink_payload.get('failed', ()))}"
415
+ f"{dest_suffix}"
416
+ )
417
+ for fail in sink_payload.get("failed") or ():
418
+ fname = fail.get("name", "?")
419
+ ferr = fail.get("error", "failed")
420
+ print(f" SINK ERROR ({fname}): {ferr}", file=sys.stderr)
421
+ return rc
422
+
423
+
424
+ def _run_accounts(args: argparse.Namespace) -> int:
425
+ try:
426
+ reg = get_plugin_registry()
427
+ provider = reg.get_provider(args.provider)
428
+ if not provider.spec.supports_accounts or not isinstance(provider, api.AccountsProvider):
429
+ raise ValueError(f"Provider {provider.spec.id!r} does not support `accounts` discovery.")
430
+ opts = _parse_opt_pairs(args.opt, provider.spec)
431
+ req = api.AccountsRequest(
432
+ login_timeout_s=float(args.login_timeout),
433
+ options=opts,
434
+ )
435
+ api.resolve_provider_target(provider, req)
436
+ host: api.Host = api.PlaywrightHost()
437
+ except ValueError as exc:
438
+ return _emit_error(
439
+ "accounts", str(exc), json_output=args.json_output, exit_code=api.EXIT_USAGE, status="usage_error", extra={"provider": args.provider}
440
+ )
441
+ except Exception as exc:
442
+ return _emit_error("accounts", str(exc), json_output=args.json_output, exit_code=api.EXIT_ERROR, extra={"provider": args.provider})
443
+
444
+ def _on_stage(name: str) -> None:
445
+ if not args.quiet and not args.json_output:
446
+ print(f"[{provider.spec.id}] stage={name}", file=sys.stderr, flush=True)
447
+
448
+ try:
449
+ accounts = asyncio.run(
450
+ api.run_async_accounts(
451
+ provider,
452
+ host,
453
+ req,
454
+ on_stage=_on_stage,
455
+ )
456
+ )
457
+ except ValueError as exc:
458
+ return _emit_error(
459
+ "accounts",
460
+ str(exc),
461
+ json_output=args.json_output,
462
+ exit_code=api.EXIT_USAGE,
463
+ status="usage_error",
464
+ extra={"provider": provider.spec.id},
465
+ )
466
+ except api.LoginTimeoutError as exc:
467
+ return _emit_error(
468
+ "accounts",
469
+ str(exc),
470
+ json_output=args.json_output,
471
+ exit_code=api.EXIT_LOGIN_TIMEOUT,
472
+ status="login_timeout",
473
+ extra={"provider": provider.spec.id},
474
+ )
475
+ except (KeyboardInterrupt, asyncio.CancelledError):
476
+ return _emit_error(
477
+ "accounts",
478
+ "Interrupted by user.",
479
+ json_output=args.json_output,
480
+ exit_code=130,
481
+ status="cancelled",
482
+ extra={"provider": provider.spec.id},
483
+ )
484
+ except Exception as exc:
485
+ return _emit_error(
486
+ "accounts", str(exc), json_output=args.json_output, exit_code=api.EXIT_ERROR, extra={"provider": provider.spec.id}
487
+ )
488
+
489
+ rows = [
490
+ {"id": a.id, "label": a.label, "owner": a.owner, "kind": a.kind, "currency": a.currency, **a.extra}
491
+ for a in accounts
492
+ ]
493
+ if args.json_output:
494
+ _emit_json({
495
+ "schema_version": _CLI_SCHEMA_VERSION,
496
+ "command": "accounts",
497
+ "provider": provider.spec.id,
498
+ "ok": True,
499
+ "status": "ok",
500
+ "exit_code": api.EXIT_OK,
501
+ "accounts": rows,
502
+ })
503
+ else:
504
+ for r in rows:
505
+ print(f"{r['id']:<16} {r['owner'] or '-':<10} {r['kind'] or '-':<12} {r['currency'] or '-':<5} {r['label']}")
506
+ return api.EXIT_OK
507
+
508
+
509
+ def _run_upload(args: argparse.Namespace) -> int:
510
+ manifest_paths: list[Path] = []
511
+ invalid_paths: list[str] = []
512
+ for p in args.paths:
513
+ if p.is_dir() and (p / "manifest.json").is_file():
514
+ manifest_paths.append(p / "manifest.json")
515
+ elif p.is_file() and p.suffix.lower() == ".json":
516
+ manifest_paths.append(p)
517
+ else:
518
+ invalid_paths.append(str(p))
519
+
520
+ if invalid_paths:
521
+ return _emit_error(
522
+ "upload",
523
+ f"Not a staging directory or manifest.json: {', '.join(invalid_paths)}",
524
+ json_output=args.json_output,
525
+ exit_code=api.EXIT_USAGE,
526
+ status="usage_error",
527
+ )
528
+
529
+ if args.local_only:
530
+ validated: list[dict[str, Any]] = []
531
+ ok_local = True
532
+ for mp in manifest_paths:
533
+ try:
534
+ res = api.verify_manifest_artifacts(mp)
535
+ if not res["ok"]:
536
+ ok_local = False
537
+ validated.append(res)
538
+ except Exception as exc:
539
+ ok_local = False
540
+ validated.append({"manifest": str(mp), "ok": False, "error": str(exc)})
541
+ rc = api.EXIT_OK if ok_local else api.EXIT_ERROR
542
+ if args.json_output:
543
+ _emit_json({
544
+ "schema_version": _CLI_SCHEMA_VERSION,
545
+ "command": "upload",
546
+ "sink": "local-only",
547
+ "ok": ok_local,
548
+ "status": "local_only" if ok_local else "error",
549
+ "exit_code": rc,
550
+ "manifests": validated,
551
+ })
552
+ else:
553
+ for item in validated:
554
+ print(f"[local-only] {item['manifest']} ok={item['ok']}")
555
+ return rc
556
+
557
+ try:
558
+ reg = get_plugin_registry()
559
+ raw_sink = (args.sink or "auto").strip().lower()
560
+ sink_id = "dir" if raw_sink == "auto" else raw_sink
561
+ sink_obj = reg.get_sink(sink_id)
562
+ cfg = _parse_sink_opts(args)
563
+ sink_obj.validate_config(cfg)
564
+ except ValueError as exc:
565
+ return _emit_error("upload", str(exc), json_output=args.json_output, exit_code=api.EXIT_USAGE, status="usage_error")
566
+ except Exception as exc:
567
+ return _emit_error("upload", str(exc), json_output=args.json_output, exit_code=api.EXIT_ERROR)
568
+
569
+ results: list[dict[str, Any]] = []
570
+ ok_all = True
571
+ for mp in manifest_paths:
572
+ try:
573
+ sres = sink_obj.deliver(mp, config=cfg, dry_run=args.dry_run)
574
+ if not sres.ok:
575
+ ok_all = False
576
+ results.append(sres.to_dict())
577
+ except Exception as exc:
578
+ ok_all = False
579
+ results.append({
580
+ "sink": sink_obj.id,
581
+ "ok": False,
582
+ "status": "error",
583
+ "manifest": str(mp),
584
+ "error": str(exc),
585
+ })
586
+
587
+ rc = api.EXIT_OK if ok_all else api.EXIT_ERROR
588
+ if args.json_output:
589
+ _emit_json({
590
+ "schema_version": _CLI_SCHEMA_VERSION,
591
+ "command": "upload",
592
+ "sink": sink_obj.id,
593
+ "ok": ok_all,
594
+ "status": "ok" if ok_all else "error",
595
+ "exit_code": rc,
596
+ "results": results,
597
+ })
598
+ else:
599
+ for r in results:
600
+ if "error" in r:
601
+ print(f"[{sink_obj.id}] ok=False error={r['error']}", file=sys.stderr)
602
+ else:
603
+ print(
604
+ f"[{sink_obj.id}] ok={r['ok']} delivered={len(r.get('delivered', ()))} "
605
+ f"skipped={len(r.get('skipped', ()))} failed={len(r.get('failed', ()))}"
606
+ )
607
+ return rc
608
+
609
+
610
+ def build_subcommand_parser() -> argparse.ArgumentParser:
611
+ p = argparse.ArgumentParser(
612
+ prog="statement-fetch",
613
+ description="Zero-LLM-in-Bank async statement fetcher, validator, and pluggable sink runner.",
614
+ )
615
+ sub = p.add_subparsers(dest="command", required=True)
616
+
617
+ ft = sub.add_parser("fetch", help="Fetch statements from an automated provider (e.g. example-bank).")
618
+ ft.add_argument("provider", help="Provider id (see `statement-fetch providers`).")
619
+ ft.add_argument("--month", default="", help="Target close month YYYY-MM (default: previous calendar month).")
620
+ ft.add_argument("--from", dest="date_from", default="", help="Filter start date (YYYY-MM-DD or DD/MM/YYYY).")
621
+ ft.add_argument("--to", dest="date_to", default="", help="Filter end date (YYYY-MM-DD or DD/MM/YYYY; default: today).")
622
+ ft.add_argument("--artifacts", default="", help="Comma-separated artifacts (default: provider defaults).")
623
+ ft.add_argument("--accounts", default="all", help="Comma-separated account filters, or 'all'.")
624
+ ft.add_argument(
625
+ "--output-dir",
626
+ type=Path,
627
+ default=None,
628
+ help="Staging directory for verified files (existing files are never overwritten; pass --skip-existing to reuse valid existing files).",
629
+ )
630
+ ft.add_argument("--skip-existing", action="store_true", help="Reuse valid matching files already in --output-dir.")
631
+ ft.add_argument("--dry-run", action="store_true", help="Validate options and print execution plan without launching a browser.")
632
+ ft.add_argument("--login-timeout", type=float, default=600.0, help="Seconds to wait for login (default: 600).")
633
+ ft.add_argument("--upload", action="store_true", help="Deliver staged files to the target sink after fetching.")
634
+ ft.add_argument("--dry-run-upload", action="store_true", help="Run sink dry-run after fetching (retains staged files).")
635
+ ft.add_argument("--sink", default="auto", help="Upload sink: auto (dir), dir, or any installed sink id.")
636
+ ft.add_argument("--sink-dir", type=Path, default=None, help="Output directory for --sink dir.")
637
+ ft.add_argument("--sink-opt", action="append", default=[], metavar="KEY=VALUE", help="Sink-specific option (repeatable).")
638
+ ft.add_argument("--opt", action="append", default=[], metavar="KEY=VALUE", help="Provider-specific option (repeatable).")
639
+ ft.add_argument("--json", dest="json_output", action="store_true", help="Emit machine-readable JSON to stdout.")
640
+ ft.add_argument("--quiet", action="store_true", help="Suppress human progress messages.")
641
+
642
+ ac = sub.add_parser("accounts", help="Discover and list accounts for an automated provider.")
643
+ ac.add_argument("provider", help="Provider id (see `statement-fetch providers`).")
644
+ ac.add_argument("--opt", action="append", default=[], metavar="KEY=VALUE", help="Provider-specific option (repeatable).")
645
+ ac.add_argument("--login-timeout", type=float, default=600.0, help="Seconds to wait for login (default: 600).")
646
+ ac.add_argument("--json", dest="json_output", action="store_true", help="Emit machine-readable JSON to stdout.")
647
+ ac.add_argument("--quiet", action="store_true", help="Suppress human progress messages.")
648
+
649
+ pr = sub.add_parser("providers", help="List installed providers, login URLs, and supported artifacts.")
650
+ pr.add_argument("--json", dest="json_output", action="store_true")
651
+
652
+ up = sub.add_parser("upload", help="Verify staged manifest(s) and deliver artifacts to a configured sink.")
653
+ up.add_argument("paths", nargs="+", type=Path, metavar="MANIFEST_OR_DIR", help="Staging directory or manifest.json path.")
654
+ up.add_argument("--sink", default="auto", help="Upload sink id (default: auto -> dir).")
655
+ up.add_argument("--sink-dir", type=Path, default=None, help="Output directory when delivering to --sink dir.")
656
+ up.add_argument("--sink-opt", action="append", default=[], metavar="KEY=VALUE", help="Sink-specific option (repeatable).")
657
+ up.add_argument("--local-only", action="store_true", help="Verify manifest schema, files, and SHA-256 locally without delivering.")
658
+ up.add_argument("--dry-run", action="store_true", help="Run sink dry-run without mutating destination state.")
659
+ up.add_argument("--json", dest="json_output", action="store_true")
660
+
661
+ doc = sub.add_parser("doctor", help="Preflight check for plugins and Playwright availability.")
662
+ doc.add_argument("--json", dest="json_output", action="store_true")
663
+
664
+ insp = sub.add_parser("inspect", help="Validate and preview local statement files.")
665
+ insp.add_argument("files", nargs="+", type=Path, metavar="FILE")
666
+ insp.add_argument("--json", dest="json_output", action="store_true")
667
+
668
+ return p
669
+
670
+
671
+ def main(argv: list[str] | None = None) -> int:
672
+ raw_argv = list(sys.argv[1:] if argv is None else argv)
673
+ args = build_subcommand_parser().parse_args(raw_argv)
674
+ if args.command == "doctor":
675
+ return run_doctor(json_output=args.json_output)
676
+ if args.command == "inspect":
677
+ return run_inspect(args.files, json_output=args.json_output)
678
+ if args.command == "providers":
679
+ return run_providers(json_output=args.json_output)
680
+ if args.command == "upload":
681
+ return _run_upload(args)
682
+ if args.command == "fetch":
683
+ return _run_fetch(args)
684
+ if args.command == "accounts":
685
+ return _run_accounts(args)
686
+ return api.EXIT_USAGE