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.
@@ -0,0 +1,126 @@
1
+ """statement-fetch: Zero-LLM-in-Bank async statement fetcher, validator, and pluggable sink runner."""
2
+ from __future__ import annotations
3
+
4
+ from . import api
5
+ from .api import (
6
+ API_VERSION,
7
+ EXIT_ERROR,
8
+ EXIT_LOGIN_TIMEOUT,
9
+ EXIT_OK,
10
+ EXIT_PARTIAL,
11
+ EXIT_USAGE,
12
+ MANIFEST_SCHEMA_VERSION,
13
+ PROVIDER_ENTRY_POINT_GROUP,
14
+ SINK_ENTRY_POINT_GROUP,
15
+ AccountInfo,
16
+ AccountsProvider,
17
+ AccountsRequest,
18
+ Artifact,
19
+ ArtifactSpec,
20
+ Click,
21
+ DownloadMismatchError,
22
+ DownloadTimeoutError,
23
+ DownloadTrigger,
24
+ DuplicatePluginError,
25
+ Evaluate,
26
+ FetchRequest,
27
+ FetchResult,
28
+ FrameLocator,
29
+ Host,
30
+ Keyboard,
31
+ Locator,
32
+ LoginTimeoutError,
33
+ ManifestArtifact,
34
+ OptionSpec,
35
+ Page,
36
+ PlaywrightHost,
37
+ PluginRegistry,
38
+ Provider,
39
+ ProviderSpec,
40
+ Sink,
41
+ SinkResult,
42
+ Stage,
43
+ TargetResolvingProvider,
44
+ ValidationResult,
45
+ ValidatorFn,
46
+ WindowClosedError,
47
+ iter_verified_manifest_artifacts,
48
+ load_manifest,
49
+ open_private_exclusive,
50
+ parse_provider_options,
51
+ publish_exclusive_file,
52
+ resolve_date_range,
53
+ resolve_provider_target,
54
+ run_async_accounts,
55
+ run_async_fetch,
56
+ sanitize_filename,
57
+ sha256_file,
58
+ validate_csv,
59
+ validate_fetch_request,
60
+ validate_json,
61
+ validate_pdf,
62
+ validate_zip,
63
+ verify_manifest_artifacts,
64
+ )
65
+
66
+ __all__ = [
67
+ "API_VERSION",
68
+ "EXIT_ERROR",
69
+ "EXIT_LOGIN_TIMEOUT",
70
+ "EXIT_OK",
71
+ "EXIT_PARTIAL",
72
+ "EXIT_USAGE",
73
+ "MANIFEST_SCHEMA_VERSION",
74
+ "PROVIDER_ENTRY_POINT_GROUP",
75
+ "SINK_ENTRY_POINT_GROUP",
76
+ "AccountInfo",
77
+ "AccountsProvider",
78
+ "AccountsRequest",
79
+ "Artifact",
80
+ "ArtifactSpec",
81
+ "Click",
82
+ "DownloadMismatchError",
83
+ "DownloadTimeoutError",
84
+ "DownloadTrigger",
85
+ "DuplicatePluginError",
86
+ "Evaluate",
87
+ "FetchRequest",
88
+ "FetchResult",
89
+ "FrameLocator",
90
+ "Host",
91
+ "Keyboard",
92
+ "Locator",
93
+ "LoginTimeoutError",
94
+ "ManifestArtifact",
95
+ "OptionSpec",
96
+ "Page",
97
+ "PlaywrightHost",
98
+ "PluginRegistry",
99
+ "Provider",
100
+ "ProviderSpec",
101
+ "Sink",
102
+ "SinkResult",
103
+ "Stage",
104
+ "TargetResolvingProvider",
105
+ "ValidationResult",
106
+ "ValidatorFn",
107
+ "WindowClosedError",
108
+ "api",
109
+ "iter_verified_manifest_artifacts",
110
+ "load_manifest",
111
+ "open_private_exclusive",
112
+ "parse_provider_options",
113
+ "publish_exclusive_file",
114
+ "resolve_date_range",
115
+ "resolve_provider_target",
116
+ "run_async_accounts",
117
+ "run_async_fetch",
118
+ "sanitize_filename",
119
+ "sha256_file",
120
+ "validate_csv",
121
+ "validate_fetch_request",
122
+ "validate_json",
123
+ "validate_pdf",
124
+ "validate_zip",
125
+ "verify_manifest_artifacts",
126
+ ]
@@ -0,0 +1,532 @@
1
+ """Core public protocols, dataclasses, typed errors, and date-range parsing for `statement-fetch`."""
2
+ from __future__ import annotations
3
+
4
+ import calendar
5
+ import re
6
+ from collections.abc import Callable, Mapping
7
+ from dataclasses import dataclass, field
8
+ from datetime import date, datetime, timedelta
9
+ from pathlib import Path
10
+ from typing import TYPE_CHECKING, Any, Literal, Protocol, runtime_checkable
11
+ from urllib.parse import urlsplit
12
+
13
+ if TYPE_CHECKING:
14
+ from ._staging import Stage
15
+
16
+ API_VERSION = 1
17
+ MANIFEST_SCHEMA_VERSION = 1
18
+ PROVIDER_ENTRY_POINT_GROUP = "statement_fetch.providers"
19
+ SINK_ENTRY_POINT_GROUP = "statement_fetch.sinks"
20
+
21
+ EXIT_OK = 0
22
+ EXIT_ERROR = 1
23
+ EXIT_USAGE = 2
24
+ EXIT_LOGIN_TIMEOUT = 3
25
+ EXIT_PARTIAL = 4
26
+
27
+ _PROVIDER_ID_RE = re.compile(r"^[a-z][a-z0-9-]{0,62}$")
28
+ _ARTIFACT_ID_RE = re.compile(r"^[a-z][a-z0-9_-]{0,62}$")
29
+ _HOSTNAME_RE = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$")
30
+
31
+
32
+ def is_valid_host(host: str) -> bool:
33
+ """Return True when `host` is a bare lowercase hostname or loopback literal (no scheme/port/path)."""
34
+ if not isinstance(host, str) or not host or host != host.strip() or any(ord(c) < 32 for c in host):
35
+ return False
36
+ low = host.lower().rstrip(".")
37
+ if not low or "://" in low or "/" in low or "\\" in low or ":" in low and low != "::1":
38
+ return False
39
+ if low in ("127.0.0.1", "localhost", "::1"):
40
+ return True
41
+ return bool(_HOSTNAME_RE.fullmatch(low))
42
+
43
+
44
+ def allowed_document_url(url: str, *, hosts: tuple[str, ...]) -> bool:
45
+ """Allow only HTTPS (or loopback HTTP for local fixtures) on `hosts`, plus internal blank/data/blob URLs."""
46
+ if not url or "\\" in url or any(ord(c) < 32 for c in url):
47
+ return False
48
+ if url.startswith(("about:", "data:", "blob:")):
49
+ return True
50
+ try:
51
+ parts = urlsplit(url)
52
+ except ValueError:
53
+ return False
54
+ host = (parts.hostname or "").lower().rstrip(".")
55
+ if parts.username is not None or parts.password is not None or not host:
56
+ return False
57
+ if parts.scheme == "http" and host in ("127.0.0.1", "localhost", "::1"):
58
+ return any(host == h.lower().strip(".") for h in hosts if h and h.strip("."))
59
+ if parts.scheme != "https":
60
+ return False
61
+ return any(
62
+ host == norm or host.endswith("." + norm)
63
+ for h in hosts
64
+ if (norm := h.lower().strip("."))
65
+ )
66
+
67
+
68
+ # ---------------------------------------------------------------------------
69
+ # Typed errors
70
+ # ---------------------------------------------------------------------------
71
+
72
+
73
+ class DownloadTimeoutError(RuntimeError):
74
+ """Raised when a triggered browser download does not arrive before timeout."""
75
+
76
+
77
+ class DownloadMismatchError(RuntimeError):
78
+ """Raised when a downloaded file does not match the expected suffix or constraints."""
79
+
80
+
81
+ class WindowClosedError(RuntimeError):
82
+ """Raised when the browser window is closed before sign-in completes."""
83
+
84
+
85
+ class LoginTimeoutError(TimeoutError):
86
+ """Raised when human login does not complete within `login_timeout_s`."""
87
+
88
+
89
+ class DuplicatePluginError(RuntimeError):
90
+ """Raised when two plugins register the same provider or sink ID."""
91
+
92
+
93
+ # ---------------------------------------------------------------------------
94
+ # Declarative download triggers
95
+ # ---------------------------------------------------------------------------
96
+
97
+
98
+ @dataclass(frozen=True)
99
+ class Click:
100
+ """Trigger a download by clicking a selector (optionally inside nested `frames`)."""
101
+
102
+ selector: str
103
+ timeout_ms: int = 10_000
104
+ frames: tuple[str, ...] = ()
105
+ force: bool = False
106
+ nth: int = 0
107
+
108
+
109
+ @dataclass(frozen=True)
110
+ class Evaluate:
111
+ """Trigger a download by evaluating a JS expression in the page main world."""
112
+
113
+ expression: str
114
+ arg: Any = None
115
+
116
+
117
+ DownloadTrigger = Click | Evaluate
118
+
119
+
120
+ # ---------------------------------------------------------------------------
121
+ # Async Page & Host protocols
122
+ # ---------------------------------------------------------------------------
123
+
124
+
125
+ class Locator(Protocol):
126
+ def first(self) -> Locator: ...
127
+ def nth(self, index: int) -> Locator: ...
128
+ async def count(self) -> int: ...
129
+ async def click(self, *, timeout_ms: int = 10_000, force: bool = False) -> None: ...
130
+ async def fill(self, value: str, *, timeout_ms: int = 10_000) -> None: ...
131
+ async def select_option(self, value: str, *, timeout_ms: int = 10_000) -> None: ...
132
+ async def press(self, key: str, *, timeout_ms: int = 5_000) -> None: ...
133
+ async def inner_text(self, *, timeout_ms: int = 5_000) -> str: ...
134
+ async def get_attribute(self, name: str, *, timeout_ms: int = 5_000) -> str | None: ...
135
+
136
+
137
+ class FrameLocator(Protocol):
138
+ def locator(self, selector: str) -> Locator: ...
139
+ def frame_locator(self, selector: str) -> FrameLocator: ...
140
+
141
+
142
+ class Keyboard(Protocol):
143
+ async def press(self, key: str) -> None: ...
144
+ async def type(self, text: str) -> None: ...
145
+
146
+
147
+ class Page(Protocol):
148
+ @property
149
+ def keyboard(self) -> Keyboard: ...
150
+ async def url(self) -> str: ...
151
+ async def goto(self, url: str, *, wait_until: str = "domcontentloaded", timeout_ms: int = 25_000) -> None: ...
152
+ async def evaluate(self, expression: str, arg: Any = None, *, timeout_s: float = 60.0) -> Any: ...
153
+ def locator(self, selector: str) -> Locator: ...
154
+ def frame_locator(self, selector: str) -> FrameLocator: ...
155
+ async def wait_for_selector(self, selector: str, *, timeout_ms: int = 15_000) -> None: ...
156
+ async def sleep(self, seconds: float) -> None: ...
157
+ async def download(
158
+ self,
159
+ trigger: DownloadTrigger,
160
+ *,
161
+ suffixes: tuple[str, ...] = (),
162
+ timeout_s: float = 30.0,
163
+ ) -> Path: ...
164
+ async def fetch_bytes(
165
+ self,
166
+ url: str,
167
+ *,
168
+ same_origin_only: bool = True,
169
+ timeout_s: float = 45.0,
170
+ max_bytes: int = 32 * 1024 * 1024,
171
+ ) -> tuple[bytes, str]: ...
172
+
173
+
174
+ @runtime_checkable
175
+ class Host(Protocol):
176
+ name: str
177
+
178
+ async def open(self, url: str, *, allowed_hosts: tuple[str, ...]) -> Page: ...
179
+ async def close(self) -> None: ...
180
+
181
+
182
+ # ---------------------------------------------------------------------------
183
+ # Validation, specification, request, artifact, and result contracts
184
+ # ---------------------------------------------------------------------------
185
+
186
+
187
+ @dataclass(frozen=True)
188
+ class ValidationResult:
189
+ valid: bool
190
+ kind: str = "other"
191
+ rows: int = 0
192
+ date_from: str = ""
193
+ date_to: str = ""
194
+ currency: str = ""
195
+ error: str = ""
196
+
197
+
198
+ ValidatorFn = Callable[[Path], ValidationResult]
199
+
200
+
201
+ @dataclass(frozen=True)
202
+ class ArtifactSpec:
203
+ id: str
204
+ default: bool = True
205
+ description: str = ""
206
+ validator: ValidatorFn | None = None
207
+ aliases: tuple[str, ...] = ()
208
+
209
+
210
+ @dataclass(frozen=True)
211
+ class AccountInfo:
212
+ id: str
213
+ label: str = ""
214
+ owner: str = ""
215
+ kind: str = ""
216
+ currency: str = ""
217
+ extra: dict[str, Any] = field(default_factory=dict)
218
+
219
+
220
+ @dataclass(frozen=True)
221
+ class AccountsRequest:
222
+ login_timeout_s: float = 600.0
223
+ options: dict[str, Any] = field(default_factory=dict)
224
+
225
+
226
+ @dataclass(frozen=True)
227
+ class OptionSpec:
228
+ name: str
229
+ type: Literal["str", "bool", "int"] = "str"
230
+ default: str | bool | int = ""
231
+ choices: tuple[str, ...] = ()
232
+ help: str = ""
233
+
234
+ def __post_init__(self) -> None:
235
+ if not self.name or not self.name.strip() or self.name != self.name.strip():
236
+ raise ValueError(f"Invalid option name: {self.name!r}")
237
+ if self.type not in ("str", "bool", "int"):
238
+ raise ValueError(f"Unsupported option type {self.type!r} for option {self.name!r}")
239
+ if self.type == "bool":
240
+ if not isinstance(self.default, bool):
241
+ raise ValueError(f"Bool option {self.name!r} default must be bool, got {self.default!r}")
242
+ elif self.type == "int":
243
+ if isinstance(self.default, bool) or not isinstance(self.default, int):
244
+ raise ValueError(f"Int option {self.name!r} default must be int, got {self.default!r}")
245
+ else:
246
+ if not isinstance(self.default, str):
247
+ raise ValueError(f"Str option {self.name!r} default must be str, got {self.default!r}")
248
+ if self.choices and self.default and self.default not in self.choices:
249
+ raise ValueError(f"Default {self.default!r} for option {self.name!r} not in choices {self.choices!r}")
250
+
251
+
252
+ @dataclass(frozen=True)
253
+ class ProviderSpec:
254
+ id: str
255
+ display_name: str
256
+ login_url: str
257
+ allowed_hosts: tuple[str, ...]
258
+ artifacts: tuple[ArtifactSpec, ...]
259
+ options: tuple[OptionSpec, ...] = ()
260
+ supports_accounts: bool = False
261
+
262
+ def __post_init__(self) -> None:
263
+ if not self.id or not _PROVIDER_ID_RE.fullmatch(self.id):
264
+ raise ValueError(f"Invalid provider id: {self.id!r}")
265
+ if not self.allowed_hosts:
266
+ raise ValueError(f"Provider {self.id!r} must declare non-empty allowed_hosts.")
267
+ for h in self.allowed_hosts:
268
+ if not is_valid_host(h):
269
+ raise ValueError(f"Provider {self.id!r} has invalid allowed_host: {h!r}")
270
+ if not self.login_url or self.login_url.startswith(("about:", "data:", "blob:")) or not allowed_document_url(
271
+ self.login_url, hosts=self.allowed_hosts
272
+ ):
273
+ raise ValueError(
274
+ f"Provider {self.id!r} login_url {self.login_url!r} is not an allowed HTTPS/loopback URL on {self.allowed_hosts!r}"
275
+ )
276
+ if not self.artifacts:
277
+ raise ValueError(f"Provider {self.id!r} must declare at least one ArtifactSpec.")
278
+ seen_arts: set[str] = set()
279
+ for art in self.artifacts:
280
+ if not art.id or not _ARTIFACT_ID_RE.fullmatch(art.id):
281
+ raise ValueError(f"Provider {self.id!r} has invalid artifact id: {art.id!r}")
282
+ if art.id in seen_arts:
283
+ raise ValueError(f"Provider {self.id!r} declares duplicate artifact id: {art.id!r}")
284
+ seen_arts.add(art.id)
285
+ seen_opts: set[str] = set()
286
+ for opt in self.options:
287
+ if opt.name in seen_opts:
288
+ raise ValueError(f"Provider {self.id!r} declares duplicate option name: {opt.name!r}")
289
+ seen_opts.add(opt.name)
290
+
291
+ def default_artifact_ids(self) -> tuple[str, ...]:
292
+ return tuple(a.id for a in self.artifacts if a.default) or tuple(a.id for a in self.artifacts)
293
+
294
+ def artifact_map(self) -> dict[str, ArtifactSpec]:
295
+ return {a.id: a for a in self.artifacts}
296
+
297
+ def to_dict(self) -> dict[str, Any]:
298
+ """Return JSON-serializable capability metadata (excluding validator callables)."""
299
+ return {
300
+ "id": self.id,
301
+ "display_name": self.display_name,
302
+ "login_url": self.login_url,
303
+ "allowed_hosts": list(self.allowed_hosts),
304
+ "artifacts": [
305
+ {
306
+ "id": a.id,
307
+ "default": bool(a.default),
308
+ "description": a.description,
309
+ "aliases": list(a.aliases),
310
+ }
311
+ for a in self.artifacts
312
+ ],
313
+ "options": [
314
+ {
315
+ "name": o.name,
316
+ "type": o.type,
317
+ "default": o.default,
318
+ "choices": list(o.choices),
319
+ "help": o.help,
320
+ }
321
+ for o in self.options
322
+ ],
323
+ "supports_accounts": bool(self.supports_accounts),
324
+ }
325
+
326
+ def resolve_artifacts(self, requested: tuple[str, ...] | list[str]) -> tuple[str, ...]:
327
+ """Resolve requested artifact tokens (supporting `all`/`*` and `ArtifactSpec.aliases`)."""
328
+ tokens = [t.strip().lower() for t in requested if (t or "").strip()]
329
+ if not tokens:
330
+ return self.default_artifact_ids()
331
+ by_id = self.artifact_map()
332
+ alias_map: dict[str, list[str]] = {}
333
+ for art in self.artifacts:
334
+ for alias in art.aliases:
335
+ alias_map.setdefault(alias.strip().lower(), []).append(art.id)
336
+ resolved: list[str] = []
337
+ unknown: list[str] = []
338
+ for tok in tokens:
339
+ if tok in ("all", "*"):
340
+ for aid in by_id:
341
+ if aid not in resolved:
342
+ resolved.append(aid)
343
+ continue
344
+ if tok in by_id:
345
+ if tok not in resolved:
346
+ resolved.append(tok)
347
+ continue
348
+ if tok in alias_map:
349
+ for aid in alias_map[tok]:
350
+ if aid not in resolved:
351
+ resolved.append(aid)
352
+ continue
353
+ unknown.append(tok)
354
+ if unknown:
355
+ raise ValueError(
356
+ f"Unknown artifact(s) for provider {self.id!r}: {', '.join(unknown)}. "
357
+ f"Supported: {', '.join(by_id)} (or all)"
358
+ )
359
+ return tuple(resolved)
360
+
361
+
362
+ @dataclass(frozen=True)
363
+ class FetchRequest:
364
+ period_start: date
365
+ period_end: date
366
+ explicit_range: bool = False
367
+ artifacts: tuple[str, ...] = ()
368
+ accounts: tuple[str, ...] = ()
369
+ options: dict[str, Any] = field(default_factory=dict)
370
+ login_timeout_s: float = 600.0
371
+ skip_existing: bool = False
372
+
373
+
374
+ @dataclass(frozen=True)
375
+ class Artifact:
376
+ artifact_id: str
377
+ path: Path
378
+ name: str
379
+ sha256: str
380
+ bytes: int
381
+ provider: str
382
+ kind: str
383
+ period: str
384
+ currency: str = ""
385
+ valid: bool = True
386
+ error: str = ""
387
+ observed_start: str = ""
388
+ observed_end: str = ""
389
+ meta: dict[str, str] = field(default_factory=dict)
390
+
391
+ def to_manifest_dict(self) -> dict[str, Any]:
392
+ """Serialize artifact metadata using a portable path relative to `manifest.json`."""
393
+ out: dict[str, Any] = {
394
+ "artifact_id": self.artifact_id,
395
+ "name": self.name,
396
+ "path": self.name,
397
+ "sha256": self.sha256,
398
+ "bytes": self.bytes,
399
+ "provider": self.provider,
400
+ "kind": self.kind,
401
+ "period": self.period,
402
+ "valid": self.valid,
403
+ }
404
+ for key in ("currency", "error", "observed_start", "observed_end"):
405
+ val = getattr(self, key)
406
+ if val:
407
+ out[key] = val
408
+ if self.meta:
409
+ out["meta"] = dict(self.meta)
410
+ return out
411
+
412
+
413
+ @dataclass(frozen=True)
414
+ class FetchResult:
415
+ provider: str
416
+ status: Literal["ok", "empty", "partial", "login_timeout", "error"]
417
+ stage_dir: Path | None
418
+ manifest_path: Path | None
419
+ artifacts: tuple[Artifact, ...] = ()
420
+ skipped: tuple[dict[str, str], ...] = ()
421
+ errors: tuple[str, ...] = ()
422
+ timings_s: dict[str, float] = field(default_factory=dict)
423
+
424
+ @property
425
+ def ok(self) -> bool:
426
+ return self.status in ("ok", "empty")
427
+
428
+
429
+ @dataclass(frozen=True)
430
+ class SinkResult:
431
+ sink_id: str
432
+ ok: bool
433
+ status: str
434
+ delivered: tuple[str, ...] = ()
435
+ failed: tuple[dict[str, str], ...] = ()
436
+ skipped: tuple[str, ...] = ()
437
+ details: dict[str, Any] = field(default_factory=dict)
438
+
439
+ def to_dict(self) -> dict[str, Any]:
440
+ return {
441
+ "sink": self.sink_id,
442
+ "ok": self.ok,
443
+ "status": self.status,
444
+ "delivered": list(self.delivered),
445
+ "skipped": list(self.skipped),
446
+ "failed": list(self.failed),
447
+ "details": dict(self.details),
448
+ }
449
+
450
+
451
+ # ---------------------------------------------------------------------------
452
+ # Provider & Sink protocols
453
+ # ---------------------------------------------------------------------------
454
+
455
+
456
+ @runtime_checkable
457
+ class Provider(Protocol):
458
+ spec: ProviderSpec
459
+
460
+ async def is_logged_in(self, page: Page) -> bool: ...
461
+ async def fetch(self, page: Page, req: FetchRequest, stage: Stage) -> None: ...
462
+ async def logoff(self, page: Page) -> None: ...
463
+
464
+
465
+ @runtime_checkable
466
+ class AccountsProvider(Provider, Protocol):
467
+ async def accounts(self, page: Page, req: AccountsRequest) -> list[AccountInfo]: ...
468
+
469
+
470
+ @runtime_checkable
471
+ class TargetResolvingProvider(Provider, Protocol):
472
+ def resolve_target(self, req: FetchRequest | AccountsRequest) -> tuple[str, tuple[str, ...]]: ...
473
+
474
+
475
+ @runtime_checkable
476
+ class Sink(Protocol):
477
+ id: str
478
+
479
+ def validate_config(self, config: Mapping[str, str] | None = None) -> None: ...
480
+ def deliver(
481
+ self,
482
+ manifest_path: Path,
483
+ *,
484
+ config: Mapping[str, str] | None = None,
485
+ dry_run: bool = False,
486
+ ) -> SinkResult: ...
487
+
488
+
489
+ # ---------------------------------------------------------------------------
490
+ # Date range resolution
491
+ # ---------------------------------------------------------------------------
492
+
493
+
494
+ def _parse_date(raw: str, flag: str) -> date:
495
+ text = (raw or "").strip()
496
+ for fmt in ("%Y-%m-%d", "%d/%m/%Y"):
497
+ try:
498
+ return datetime.strptime(text, fmt).date()
499
+ except ValueError:
500
+ continue
501
+ raise ValueError(f"Invalid {flag} {raw!r}; expected YYYY-MM-DD or DD/MM/YYYY.")
502
+
503
+
504
+ def resolve_date_range(
505
+ *,
506
+ month_str: str = "",
507
+ date_from_str: str = "",
508
+ date_to_str: str = "",
509
+ today: date | None = None,
510
+ ) -> tuple[date, date, bool]:
511
+ """Resolve CLI/service period arguments into `(period_start, period_end, is_explicit_range)`."""
512
+ if month_str and (date_from_str or date_to_str):
513
+ raise ValueError("Cannot combine --month with --from / --to.")
514
+ if date_to_str and not date_from_str:
515
+ raise ValueError("--to requires --from.")
516
+ if date_from_str:
517
+ start = _parse_date(date_from_str, "--from")
518
+ end = _parse_date(date_to_str, "--to") if date_to_str else (today or date.today())
519
+ if start > end:
520
+ raise ValueError(f"--from ({start.isoformat()}) must be on or before --to ({end.isoformat()}).")
521
+ return start, end, True
522
+ if month_str:
523
+ cleaned_month = month_str.strip()
524
+ if not re.fullmatch(r"\d{4}-\d{2}", cleaned_month):
525
+ raise ValueError(f"Invalid --month {month_str!r}; expected YYYY-MM.")
526
+ y, m = int(cleaned_month[:4]), int(cleaned_month[5:7])
527
+ if not (1 <= m <= 12):
528
+ raise ValueError(f"Invalid --month {month_str!r}; month must be 01..12.")
529
+ return date(y, m, 1), date(y, m, calendar.monthrange(y, m)[1]), False
530
+ d = today or date.today()
531
+ end = d.replace(day=1) - timedelta(days=1)
532
+ return end.replace(day=1), end, False