silpo-agent-cli 0.2.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.
silpo_agent/cli.py ADDED
@@ -0,0 +1,1117 @@
1
+ """silpo-agent CLI entrypoint. `reorder` wires the pipeline together per the
2
+ PRD's module order: Address Resolver -> Cart Context Resolver -> Order
3
+ Aggregator -> Substitution Resolver -> (optional) Promo Optimizer -> Cart
4
+ Writer -> report. Cart Context Resolver resolves branchId/companyId/
5
+ deliveryType/timeslot/products/bonus_available/raw timeslot-address-shipments
6
+ (see cart_context.py); its `CartContext` is threaded through to Substitution
7
+ Resolver (issue #18, for its availability/replacement lookups), Promo
8
+ Optimizer (issue #20, for its bonus-application `silpo_update_shopping_cart`
9
+ call), and Cart Writer (issue #19, as the source of truth for the
10
+ non-empty-cart guard and the branch/company fallback on each add-to-cart
11
+ item). Cart Writer owns the non-empty cart guard (warn-and-proceed-or-abort)
12
+ and the optional `--budget` trim; the CLI only parses `--budget` and reports
13
+ the outcome. Promo Optimizer runs only when `--optimize promos` is passed --
14
+ the module isn't even called otherwise, so a plain `reorder` makes zero
15
+ promo-related MCP calls (CONTEXT.md's "Promo optimization" entry).
16
+ """
17
+
18
+ import argparse
19
+ import sys
20
+ from importlib.metadata import version
21
+
22
+ from silpo_agent.address_resolver import resolve_address
23
+ from silpo_agent.auth import MCPClient, TokenStore
24
+ from silpo_agent.cart_context import confirm_no_blocking_validations, resolve_cart_context
25
+ from silpo_agent.cart_editor import (
26
+ add_cart_item,
27
+ CartEditError,
28
+ remove_cart_item,
29
+ resolve_product_by_slug,
30
+ search_replacement_candidates,
31
+ set_cart_item_quantity,
32
+ swap_cart_item,
33
+ )
34
+ from silpo_agent.cart_viewer import format_cart
35
+ from silpo_agent.cart_writer import trim_by_source_priority, write_cart
36
+ from silpo_agent.coupons_lister import list_coupons
37
+ from silpo_agent.delivery_settings import run_delivery_settings
38
+ from silpo_agent.favorites_deals import list_favorites_deals
39
+ from silpo_agent.log_store import ReorderLogStore
40
+ from silpo_agent.norm_dataset import get_norms
41
+ from silpo_agent.norm_top_up import find_uncovered_categories, resolve_norm_top_up_items
42
+ from silpo_agent.order_aggregator import InsufficientOrderHistoryError, TypicalItem, derive_typical_items
43
+ from silpo_agent.promo_finder import find_promo_alternatives
44
+ from silpo_agent.promo_optimizer import optimize_promos
45
+ from silpo_agent.promo_scanner import CategoryNotFoundError, list_category_titles, resolve_category, scan_deals
46
+ from silpo_agent.substitution_resolver import resolve_substitutions
47
+ from silpo_agent.timeslot_format import format_timeslot
48
+
49
+
50
+ def _auto_yes_input_fn(print_fn):
51
+ """input_fn that answers every reorder prompt without a terminal attached.
52
+
53
+ Confirms the proposed default on yes/no prompts ("[y/N]", "[Y/n]") and
54
+ picks the first candidate on numbered picks ("Pick a number: "). Echoes
55
+ the prompt and its answer via print_fn so --yes runs stay auditable in
56
+ the output instead of silently deciding things.
57
+ """
58
+
59
+ def _input(prompt: str) -> str:
60
+ answer = "1" if "Pick a number:" in prompt else "y"
61
+ print_fn(f"{prompt}{answer}")
62
+ return answer
63
+
64
+ return _input
65
+
66
+
67
+ def _run_reorder(
68
+ last: int,
69
+ threshold: float,
70
+ client,
71
+ log_store,
72
+ budget: float | None = None,
73
+ optimize: str | None = None,
74
+ yes: bool = False,
75
+ print_fn=None,
76
+ ) -> int:
77
+ print_fn = print_fn or print
78
+ input_fn = _auto_yes_input_fn(print_fn) if yes else None
79
+
80
+ address = resolve_address(client, log_store, input_fn=input_fn, print_fn=print_fn)
81
+ if address is None:
82
+ print("reorder: no delivery address resolved; aborting before product search", file=sys.stderr)
83
+ return 1
84
+
85
+ # Pass the already-resolved address through so Cart Context Resolver's
86
+ # no-shipments fallback (issue #29) reuses it instead of prompting again.
87
+ cart_context = resolve_cart_context(
88
+ client, resolved_address=address, log_store=log_store, input_fn=input_fn, print_fn=print_fn
89
+ )
90
+
91
+ if address:
92
+ print_fn(f"Delivering to: {address.label}")
93
+ if cart_context.delivery_type:
94
+ print_fn(f"Delivery type: {cart_context.delivery_type}")
95
+ if cart_context.timeslot_start:
96
+ print_fn(f"Timeslot: {format_timeslot(cart_context.timeslot_start, cart_context.timeslot_end)}")
97
+ else:
98
+ print_fn("Timeslot: not set yet -- run 'silpo-agent delivery' to choose one")
99
+
100
+ if not confirm_no_blocking_validations(cart_context, input_fn=input_fn, print_fn=print_fn):
101
+ print_fn("Aborted: fix the delivery context (e.g. run 'silpo-agent delivery') and try again.")
102
+ return 1
103
+
104
+ orders_response = client.call("silpo_get_my_online_orders", {"limit": min(last, 100)}) or []
105
+ orders = orders_response.get("orders", []) if isinstance(orders_response, dict) else orders_response
106
+ try:
107
+ typical_items = derive_typical_items(orders, last=last, threshold=threshold)
108
+ except InsufficientOrderHistoryError as exc:
109
+ print(f"reorder: {exc}", file=sys.stderr)
110
+ return 1
111
+
112
+ substitution_result = resolve_substitutions(
113
+ client, log_store, typical_items, cart_context, input_fn=input_fn, print_fn=print_fn
114
+ )
115
+
116
+ items = substitution_result.items
117
+ promo_result = None
118
+ if optimize == "promos":
119
+ promo_result = optimize_promos(client, items, cart_context)
120
+ items = promo_result.items
121
+
122
+ report = write_cart(client, items, cart_context, budget=budget, input_fn=input_fn, print_fn=print_fn)
123
+
124
+ for original_id, replacement_id in substitution_result.substitutions:
125
+ print(f"Substituted {original_id} -> {replacement_id}")
126
+ if substitution_result.unavailable:
127
+ print(f"Unavailable ({len(substitution_result.unavailable)}): {', '.join(substitution_result.unavailable)}")
128
+ if promo_result is not None and promo_result.bonus_applied:
129
+ print(f"Applied {promo_result.bonus_applied:.2f} bonus points to cart")
130
+
131
+ if report.aborted:
132
+ return 1
133
+
134
+ if report.trimmed:
135
+ print(f"Trimmed {len(report.trimmed)} item(s) to fit budget {budget:.2f}:")
136
+ for product_id, price in report.trimmed:
137
+ print(f" - {product_id}: {price:.2f}")
138
+ print(f"Added {len(report.items_added)} item(s):")
139
+ for product_id, price in report.items_added:
140
+ print(f" - {product_id}: {price:.2f}")
141
+ print(f"Total: {report.total:.2f}")
142
+ print("Check your cart: https://silpo.ua/basket")
143
+ return 0
144
+
145
+
146
+ def _run_smart_cart(
147
+ last: int,
148
+ threshold: float,
149
+ client,
150
+ log_store,
151
+ yes: bool = False,
152
+ print_fn=None,
153
+ people: int = 1,
154
+ basket_type: str = "eco",
155
+ budget: float | None = None,
156
+ ) -> int:
157
+ """Ticket 02/04/05: same pipeline as `_run_reorder` (Address Resolver ->
158
+ Cart Context Resolver -> Order Aggregator -> Substitution Resolver ->
159
+ Cart Writer), plus two extra stages layered on top of the typical
160
+ items, in order: discounted favorites (Favorites Deals, ticket 02,
161
+ deduplicated by product id), then a norm top-up (ticket 04) -- for any
162
+ norm-dataset category with no real product-id overlap with what's
163
+ already going into the cart, the top search result for that norm's
164
+ product name is proposed (at `quantity_per_person * people`, rounded to
165
+ a valid step) and shown as its own list with a single [y/N] gate before
166
+ being folded into the one `write_cart` call. Declining adds nothing
167
+ from norms; typical items and favorites-deals are unaffected either
168
+ way.
169
+
170
+ Ticket 05: if --budget is set and the combined total would exceed it,
171
+ `cart_writer.trim_by_source_priority` trims norm items first (they're
172
+ guesses, not known purchases), then favorites-deals, then typical items
173
+ as the last resort -- deliberately NOT the single merged-list `budget=`
174
+ path `write_cart` offers (that trims by frequency across the whole
175
+ list at once, which would mis-order norms/favorites since both are
176
+ built with frequency=0.0). The already-trimmed list is passed to
177
+ `write_cart` with `budget=None` since the trim already happened."""
178
+ print_fn = print_fn or print
179
+ input_fn = _auto_yes_input_fn(print_fn) if yes else None
180
+
181
+ if people <= 0:
182
+ print_fn(f"smart-cart: --people must be a positive integer, got {people}")
183
+ return 1
184
+
185
+ address = resolve_address(client, log_store, input_fn=input_fn, print_fn=print_fn)
186
+ if address is None:
187
+ print("smart-cart: no delivery address resolved; aborting before product search", file=sys.stderr)
188
+ return 1
189
+
190
+ cart_context = resolve_cart_context(
191
+ client, resolved_address=address, log_store=log_store, input_fn=input_fn, print_fn=print_fn
192
+ )
193
+
194
+ if address:
195
+ print_fn(f"Delivering to: {address.label}")
196
+ if cart_context.delivery_type:
197
+ print_fn(f"Delivery type: {cart_context.delivery_type}")
198
+ if cart_context.timeslot_start:
199
+ print_fn(f"Timeslot: {format_timeslot(cart_context.timeslot_start, cart_context.timeslot_end)}")
200
+ else:
201
+ print_fn("Timeslot: not set yet -- run 'silpo-agent delivery' to choose one")
202
+
203
+ if not confirm_no_blocking_validations(cart_context, input_fn=input_fn, print_fn=print_fn):
204
+ print_fn("Aborted: fix the delivery context (e.g. run 'silpo-agent delivery') and try again.")
205
+ return 1
206
+
207
+ orders_response = client.call("silpo_get_my_online_orders", {"limit": min(last, 100)}) or []
208
+ orders = orders_response.get("orders", []) if isinstance(orders_response, dict) else orders_response
209
+ try:
210
+ typical_items = derive_typical_items(orders, last=last, threshold=threshold)
211
+ except InsufficientOrderHistoryError as exc:
212
+ print(f"smart-cart: {exc}", file=sys.stderr)
213
+ return 1
214
+
215
+ substitution_result = resolve_substitutions(
216
+ client, log_store, typical_items, cart_context, input_fn=input_fn, print_fn=print_fn
217
+ )
218
+ items = substitution_result.items
219
+ typical_ids = {item.product_id for item in items}
220
+
221
+ favorite_deals = list_favorites_deals(
222
+ client, log_store, input_fn=input_fn, print_fn=print_fn, cart_context=cart_context
223
+ )
224
+ favorite_items = [
225
+ TypicalItem(product_id=deal.product_id, frequency=0.0, last_known_price=deal.price, name=deal.name)
226
+ for deal in favorite_deals
227
+ if deal.product_id and deal.product_id not in typical_ids
228
+ ]
229
+ favorite_ids = {item.product_id for item in favorite_items}
230
+
231
+ # Ticket 04: norm top-up. Categories already covered by a typical item
232
+ # or a favorites-deal addition (real id intersection, not "did we search
233
+ # for the same id") are skipped; the rest get a proposed addition, shown
234
+ # and gated behind its own [y/N] before joining the single write_cart
235
+ # call below.
236
+ covered_ids = typical_ids | favorite_ids
237
+ norms = get_norms(basket_type)
238
+ uncovered_norms = find_uncovered_categories(client, cart_context, norms, covered_ids, print_fn=print_fn)
239
+ norm_result = resolve_norm_top_up_items(client, cart_context, uncovered_norms, people, print_fn=print_fn)
240
+ # Defensive: a norm search can in principle resurface a product already
241
+ # going into the cart (e.g. the category-coverage cap missed it) --
242
+ # dropped here rather than risking a duplicate cart line.
243
+ norm_candidates = [item for item in norm_result.items if item.product_id not in covered_ids]
244
+
245
+ norm_items: list[TypicalItem] = []
246
+ if norm_candidates:
247
+ print_fn("Adding from norms:")
248
+ for item in norm_candidates:
249
+ print_fn(f" - {item.name or item.product_id}: {item.last_known_price:.2f} x{item.quantity}")
250
+ confirm_input = input_fn or input
251
+ answer = confirm_input("Add these norm top-up items to the cart? [y/N] ").strip().lower()
252
+ if answer in ("y", "yes"):
253
+ norm_items = norm_candidates
254
+ norm_ids = {item.product_id for item in norm_items}
255
+
256
+ trimmed_by_source: list[tuple[str, str, float]] = []
257
+ if budget is not None:
258
+ already_spent = cart_context.total_after_discounts or 0.0
259
+ cart_items, trimmed_by_source = trim_by_source_priority(
260
+ [("norm", norm_items), ("favorite", favorite_items), ("typical", items)], budget, already_spent
261
+ )
262
+ else:
263
+ cart_items = items + favorite_items + norm_items
264
+
265
+ report = write_cart(client, cart_items, cart_context, input_fn=input_fn, print_fn=print_fn)
266
+
267
+ for original_id, replacement_id in substitution_result.substitutions:
268
+ print(f"Substituted {original_id} -> {replacement_id}")
269
+ if substitution_result.unavailable:
270
+ print(f"Unavailable ({len(substitution_result.unavailable)}): {', '.join(substitution_result.unavailable)}")
271
+
272
+ if report.aborted:
273
+ return 1
274
+
275
+ if trimmed_by_source:
276
+ print(f"Trimmed {len(trimmed_by_source)} item(s) to fit budget {budget:.2f}:")
277
+ for source, product_id, price in trimmed_by_source:
278
+ print(f" - [{source}] {product_id}: {price:.2f}")
279
+
280
+ # Ticket 02/04 AC: report lists typical items, favorites-deals, and norm
281
+ # additions distinctly, so the user can tell which source added what.
282
+ typical_added = [
283
+ (pid, price) for pid, price in report.items_added if pid not in favorite_ids and pid not in norm_ids
284
+ ]
285
+ favorite_added = [(pid, price) for pid, price in report.items_added if pid in favorite_ids]
286
+ norm_added = [(pid, price) for pid, price in report.items_added if pid in norm_ids]
287
+
288
+ print(f"Added {len(typical_added)} typical item(s):")
289
+ for product_id, price in typical_added:
290
+ print(f" - {product_id}: {price:.2f}")
291
+ print(f"Added {len(favorite_added)} favorited deal(s):")
292
+ for product_id, price in favorite_added:
293
+ print(f" - {product_id}: {price:.2f}")
294
+ print(f"Added {len(norm_added)} norm item(s):")
295
+ for product_id, price in norm_added:
296
+ print(f" - {product_id}: {price:.2f}")
297
+ print(f"Total: {report.total:.2f}")
298
+ print("Check your cart: https://silpo.ua/basket")
299
+ return 0
300
+
301
+
302
+ def _run_delivery(client, log_store, input_fn, print_fn) -> int:
303
+ result = run_delivery_settings(client, log_store, input_fn=input_fn, print_fn=print_fn)
304
+ return 0 if result.applied else 1
305
+
306
+
307
+ def _run_cart_edit_replace(client, cart_context, old_slug, new_slug, print_fn) -> int:
308
+ """Non-interactive swap (issue #50): both arguments are slugs. The new
309
+ one resolves through `cart_editor.resolve_product_by_slug`, a real
310
+ per-slug lookup -- the old path used the id as a free-text search query,
311
+ which issue #18 documents as usually returning nothing."""
312
+ new_product = resolve_product_by_slug(client, cart_context, new_slug)
313
+ if new_product is None:
314
+ print_fn(f"cart edit: replacement product {new_slug!r} not found")
315
+ return 1
316
+ try:
317
+ result = swap_cart_item(client, cart_context, old_slug, new_product)
318
+ except CartEditError as exc:
319
+ print_fn(f"cart edit: {exc}")
320
+ return 1
321
+ print_fn(f"Replaced {result.removed_slug} with {result.added_slug} ({result.added_price:.2f})")
322
+ return 0
323
+
324
+
325
+ def _run_cart_edit_add(client, cart_context, new_slug, print_fn, quantity: float = 1) -> int:
326
+ """Non-interactive add: adds NEW_SLUG as a brand-new cart line (quantity
327
+ --quantity, default 1), without removing anything. Errors (no MCP
328
+ mutation made) if the slug doesn't resolve, is already in the cart, or
329
+ --quantity isn't a positive number -- see add_cart_item."""
330
+ if quantity <= 0:
331
+ print_fn(f"cart edit: --quantity must be a positive number, got {quantity}")
332
+ return 1
333
+ new_product = resolve_product_by_slug(client, cart_context, new_slug)
334
+ if new_product is None:
335
+ print_fn(f"cart edit: product {new_slug!r} not found")
336
+ return 1
337
+ try:
338
+ result = add_cart_item(client, cart_context, new_product, quantity=quantity)
339
+ except CartEditError as exc:
340
+ print_fn(f"cart edit: {exc}")
341
+ return 1
342
+ quantity_display = int(quantity) if quantity == int(quantity) else quantity
343
+ print_fn(f"Added {result.added_slug} x{quantity_display} ({result.added_price:.2f} each)")
344
+ return 0
345
+
346
+
347
+ def _run_cart_edit_qty(client, cart_context, slug, quantity_str: str, print_fn) -> int:
348
+ """Non-interactive: sets SLUG's existing cart line quantity to the
349
+ absolute value NUM (a set, not a delta -- unlike --add's addQuantity=True
350
+ mechanism), zero prompts. Errors (no MCP mutation made) if NUM isn't a
351
+ positive number, or if SLUG isn't already a line in the cart -- see
352
+ set_cart_item_quantity."""
353
+ try:
354
+ quantity = float(quantity_str)
355
+ except ValueError:
356
+ print_fn(f"cart edit: --qty quantity must be a number, got {quantity_str!r}")
357
+ return 1
358
+ if quantity <= 0:
359
+ print_fn(f"cart edit: --qty quantity must be a positive number, got {quantity}")
360
+ return 1
361
+ try:
362
+ result = set_cart_item_quantity(client, cart_context, slug, quantity)
363
+ except CartEditError as exc:
364
+ print_fn(f"cart edit: {exc}")
365
+ return 1
366
+ old_display = int(result.old_quantity) if result.old_quantity == int(result.old_quantity) else result.old_quantity
367
+ new_display = int(result.new_quantity) if result.new_quantity == int(result.new_quantity) else result.new_quantity
368
+ line_total = result.added_price * result.new_quantity
369
+ print_fn(f"{result.added_slug}: {old_display} -> {new_display} ({line_total:.2f})")
370
+ return 0
371
+
372
+
373
+ def _run_cart_edit_remove(client, cart_context, slug, print_fn) -> int:
374
+ """Non-interactive delete: removes SLUG's cart line, zero prompts,
375
+ nothing added back. Errors (no MCP mutation made) if the slug isn't
376
+ actually in the cart -- see remove_cart_item."""
377
+ try:
378
+ result = remove_cart_item(client, cart_context, slug)
379
+ except CartEditError as exc:
380
+ print_fn(f"cart edit: {exc}")
381
+ return 1
382
+ print_fn(f"Removed {result.removed_slug} ({result.removed_price:.2f})")
383
+ return 0
384
+
385
+
386
+ def _pick_free_text_replacement(client, cart_context, input_fn, print_fn) -> dict | None:
387
+ """Free-text search path (issue #30): prompts for search terms, shows
388
+ matching candidates, lets the user pick one. Returns the chosen product
389
+ record, or None (with an explanatory message already printed) if the
390
+ search comes up empty or the pick is out of range."""
391
+ query = input_fn("Search for a replacement: ").strip()
392
+ candidates = search_replacement_candidates(client, cart_context, query) if query else []
393
+ if not candidates:
394
+ print_fn(f"cart edit: no results for {query!r}")
395
+ return None
396
+
397
+ print_fn("Candidates:")
398
+ for i, candidate in enumerate(candidates, start=1):
399
+ print_fn(f"{i}. {candidate.get('name')} ({candidate.get('price')})")
400
+ pick = input_fn("Pick a replacement: ").strip()
401
+ pick_idx = int(pick) if pick.isdigit() else None
402
+ if not pick_idx or not (1 <= pick_idx <= len(candidates)):
403
+ print_fn(f"No candidate numbered {pick!r}.")
404
+ return None
405
+ return candidates[pick_idx - 1]
406
+
407
+
408
+ def _pick_promo_replacement(candidates, input_fn, print_fn) -> dict | None:
409
+ """Promo-browse path (issue #31): shows the (already non-empty) list of
410
+ `PromoCandidate`s from `find_promo_alternatives` and lets the user pick
411
+ one, converted to the plain product-record shape `swap_cart_item`
412
+ expects. Returns None (with a message already printed) if the pick is
413
+ out of range."""
414
+ print_fn("Promo alternatives:")
415
+ for i, candidate in enumerate(candidates, start=1):
416
+ print_fn(f"{i}. {candidate.name}: {candidate.price:.2f} (was {candidate.old_price:.2f})")
417
+ pick = input_fn("Pick a promo alternative: ").strip()
418
+ pick_idx = int(pick) if pick.isdigit() else None
419
+ if not pick_idx or not (1 <= pick_idx <= len(candidates)):
420
+ print_fn(f"No candidate numbered {pick!r}.")
421
+ return None
422
+ chosen = candidates[pick_idx - 1]
423
+ return {
424
+ "id": chosen.product_id,
425
+ "slug": chosen.slug,
426
+ "name": chosen.name,
427
+ "price": chosen.price,
428
+ "companyId": chosen.company_id,
429
+ "branchId": chosen.branch_id,
430
+ }
431
+
432
+
433
+ def _run_cart_edit_interactive(client, cart_context, input_fn, print_fn) -> int:
434
+ if not cart_context.products:
435
+ print_fn("Your cart is empty; nothing to edit.")
436
+ return 0
437
+
438
+ print_fn("Current cart items:")
439
+ for i, product in enumerate(cart_context.products, start=1):
440
+ print_fn(f"{i}. {product.get('name') or product.get('productId')}")
441
+ choice = input_fn("Pick an item to replace: ").strip()
442
+ idx = int(choice) if choice.isdigit() else None
443
+ if not idx or not (1 <= idx <= len(cart_context.products)):
444
+ print_fn(f"No item numbered {choice!r}.")
445
+ return 1
446
+ old_product = cart_context.products[idx - 1]
447
+ old_slug = old_product.get("slug")
448
+
449
+ mode = input_fn("Replace via [1] free-text search or [2] promo alternatives? [1/2] ").strip()
450
+ if mode == "2":
451
+ promo_candidates = find_promo_alternatives(client, cart_context, old_slug) if old_slug else []
452
+ if promo_candidates:
453
+ chosen = _pick_promo_replacement(promo_candidates, input_fn, print_fn)
454
+ else:
455
+ print_fn("cart edit: no discounted alternatives found for this item; falling back to free-text search.")
456
+ chosen = _pick_free_text_replacement(client, cart_context, input_fn, print_fn)
457
+ else:
458
+ chosen = _pick_free_text_replacement(client, cart_context, input_fn, print_fn)
459
+
460
+ if chosen is None:
461
+ return 1
462
+
463
+ old_label = old_product.get("name") or old_slug
464
+ new_label = chosen.get("name") or chosen.get("slug") or chosen.get("id")
465
+ confirm = input_fn(f"Replace {old_label} with {new_label}? [y/N] ").strip().lower()
466
+ if confirm not in ("y", "yes"):
467
+ print_fn("Aborted: cart left unchanged.")
468
+ return 0
469
+
470
+ try:
471
+ result = swap_cart_item(client, cart_context, old_slug, chosen)
472
+ except CartEditError as exc:
473
+ print_fn(f"cart edit: {exc}")
474
+ return 1
475
+ # Free-text search results aren't guaranteed to carry a slug, so fall
476
+ # back to the label already shown to the user rather than printing "None".
477
+ print_fn(f"Replaced {result.removed_slug} with {result.added_slug or new_label} ({result.added_price:.2f})")
478
+ return 0
479
+
480
+
481
+ def _run_cart_edit(
482
+ client,
483
+ log_store,
484
+ input_fn,
485
+ print_fn,
486
+ replace: list[str] | None,
487
+ add: str | None = None,
488
+ quantity: float = 1,
489
+ qty: list[str] | None = None,
490
+ remove: str | None = None,
491
+ ) -> int:
492
+ cart_context = resolve_cart_context(client, input_fn=input_fn, print_fn=print_fn, log_store=log_store)
493
+ if not cart_context.shopping_cart_id:
494
+ print_fn("cart edit: no cart resolved; nothing to edit")
495
+ return 1
496
+
497
+ if replace is not None:
498
+ old_id, new_id = replace
499
+ return _run_cart_edit_replace(client, cart_context, old_id, new_id, print_fn)
500
+
501
+ if add is not None:
502
+ return _run_cart_edit_add(client, cart_context, add, print_fn, quantity=quantity)
503
+
504
+ if qty is not None:
505
+ slug, new_qty = qty
506
+ return _run_cart_edit_qty(client, cart_context, slug, new_qty, print_fn)
507
+
508
+ if remove is not None:
509
+ return _run_cart_edit_remove(client, cart_context, remove, print_fn)
510
+
511
+ # Only the interactive path (no --replace/--add/--qty/--remove flag)
512
+ # gates on validation errors -- the flag-based paths are documented as
513
+ # zero-prompt/non-interactive (SKILL.md), so blocking on `input_fn` here
514
+ # would hang automation that relies on that contract. The validation
515
+ # itself was still printed above via resolve_cart_context regardless.
516
+ if not confirm_no_blocking_validations(cart_context, input_fn=input_fn, print_fn=print_fn):
517
+ print_fn("Aborted: fix the delivery context (e.g. run 'silpo-agent delivery') and try again.")
518
+ return 1
519
+
520
+ return _run_cart_edit_interactive(client, cart_context, input_fn, print_fn)
521
+
522
+
523
+ def _run_clear_context(log_store, token_store, input_fn, print_fn, *, yes: bool = False) -> int:
524
+ if not yes:
525
+ answer = input_fn(
526
+ "This will permanently delete your local reorder history, substitution memory, and log you out "
527
+ "(cached OAuth token). Continue? [y/N] "
528
+ ).strip().lower()
529
+ if answer not in ("y", "yes"):
530
+ print_fn("Aborted: local data left unchanged.")
531
+ return 0
532
+ log_store.clear()
533
+ token_store.clear()
534
+ print_fn("Cleared local reorder history, substitution memory, and logged out.")
535
+ return 0
536
+
537
+
538
+ def _run_cart(client, log_store, input_fn, print_fn) -> int:
539
+ cart_context = resolve_cart_context(client, input_fn=input_fn, log_store=log_store, print_fn=print_fn)
540
+ for line in format_cart(cart_context):
541
+ print_fn(line)
542
+ return 0
543
+
544
+
545
+ def _run_deals(client, limit, log_store, input_fn, print_fn, category=None) -> int:
546
+ cart_context = resolve_cart_context(client, log_store=log_store, input_fn=input_fn, print_fn=print_fn)
547
+ if category is not None:
548
+ # Issue #05: warn when --category only matched via the substring
549
+ # fallback (e.g. "Вино" -> "Виноград") -- silent otherwise means the
550
+ # user only notices something's off once the results look wrong.
551
+ match = resolve_category(client, cart_context, category)
552
+ if match is not None and not match.exact:
553
+ print_fn(f'matched category "{match.title}" for query "{category}"')
554
+ try:
555
+ deals = scan_deals(client, cart_context, limit=limit, category=category)
556
+ except CategoryNotFoundError as exc:
557
+ print_fn(f"deals: no category matching {str(exc)!r} found")
558
+ return 1
559
+ if not deals:
560
+ print_fn("No current deals found.")
561
+ return 0
562
+ for deal in deals:
563
+ line = f"{deal.name}: {deal.price:.2f} (was {deal.old_price:.2f}, -{deal.discount_pct:.0f}%)"
564
+ # Issue #50: the slug is what `cart edit --replace` takes, so a deal
565
+ # is only actionable with it printed. Omitted when absent.
566
+ if deal.slug:
567
+ line += f" {deal.slug}"
568
+ print_fn(line)
569
+ return 0
570
+
571
+
572
+ def _run_deals_list_categories(client, log_store, input_fn, print_fn) -> int:
573
+ cart_context = resolve_cart_context(client, log_store=log_store, input_fn=input_fn, print_fn=print_fn)
574
+ for title in list_category_titles(client, cart_context):
575
+ print_fn(title)
576
+ return 0
577
+
578
+
579
+ def _run_coupons(client) -> int:
580
+ lines = list_coupons(client)
581
+ if not lines:
582
+ print("No active coupons found.")
583
+ return 0
584
+ for line in lines:
585
+ print(line.format())
586
+ return 0
587
+
588
+
589
+ def _run_favorites_deals(client, log_store, input_fn, print_fn) -> int:
590
+ deals = list_favorites_deals(client, log_store, input_fn=input_fn, print_fn=print_fn)
591
+ if not deals:
592
+ print_fn("No discounted favorites found.")
593
+ return 0
594
+ for deal in deals:
595
+ print_fn(deal.format())
596
+ return 0
597
+
598
+
599
+ def _run_cart_promos(client, log_store, input_fn, print_fn) -> int:
600
+ """`cart promos` (issue #28): read-only -- for every item currently in
601
+ the cart, shows real promo alternatives via the Similar-Products Promo
602
+ Finder (promo_finder.py). Never calls a cart-mutating tool."""
603
+ cart_context = resolve_cart_context(client, input_fn=input_fn, log_store=log_store, print_fn=print_fn)
604
+ if not cart_context.products:
605
+ print_fn("Your cart is empty.")
606
+ return 0
607
+
608
+ for item in cart_context.products:
609
+ name = item.get("name") or item.get("productId") or "?"
610
+ slug = item.get("slug")
611
+ # Issue #50: both halves of a swap must be addressable -- the cart
612
+ # item's slug is `--replace`'s *old* argument, each alternative's is
613
+ # the *new* one.
614
+ print_fn(f"{name}: {slug}" if slug else f"{name}:")
615
+ candidates = find_promo_alternatives(client, cart_context, slug) if slug else []
616
+ if not candidates:
617
+ print_fn(" no discounted alternatives found.")
618
+ continue
619
+ for candidate in candidates:
620
+ line = (
621
+ f" - {candidate.name}: {candidate.price:.2f} (was {candidate.old_price:.2f}, "
622
+ f"-{candidate.discount:.2f})"
623
+ )
624
+ if candidate.slug:
625
+ line += f" {candidate.slug}"
626
+ print_fn(line)
627
+ return 0
628
+
629
+
630
+ _TOP_LEVEL_EPILOG = """\
631
+ First run triggers a one-time browser login (OAuth2.1+PKCE against
632
+ mcp.silpo.ua); the token is cached in your OS keyring afterward, so
633
+ later runs don't re-prompt until it expires.
634
+
635
+ running with no subcommand is the same as 'cart': shows your current real
636
+ cart -- delivery address/type/timeslot, items, payable total, bonus balance.
637
+
638
+ commands:
639
+ cart show your current real cart: items, payable total, bonus balance (read-only)
640
+ cart edit manually replace one cart item with another, or add a new one
641
+ cart promos show real promo alternatives for every item in your cart (read-only)
642
+ reorder rebuild your cart from your typical (frequently-bought) items
643
+ smart-cart reorder, plus discounted favorites and a norm top-up (--people/--basket-type/--budget)
644
+ delivery explicitly set your delivery address, delivery type, and timeslot
645
+ clear-context wipe your local reorder history, substitution memory, and cached login
646
+ coupons list your active loyalty coupons (read-only)
647
+ deals show the best current store-wide discounts (read-only)
648
+ favorites-deals list your favorited products currently on discount (read-only)
649
+
650
+ run 'silpo-agent reorder --help' for reorder's flags and examples.
651
+ """
652
+
653
+ _CLEAR_CONTEXT_EPILOG = """\
654
+ deletes the local Reorder Log and Substitution Memory (~/.silpo-agent/
655
+ reorder_log.json) and the cached OAuth token in your OS keyring, after
656
+ asking for confirmation -- declining leaves everything untouched. Never
657
+ touches your real Silpo cart or the Silpo servers (no MCP calls). The next
658
+ command that needs a token triggers a fresh browser login.
659
+
660
+ pass --yes (-y) to skip the confirmation prompt and clear immediately.
661
+ """
662
+
663
+ _DELIVERY_EPILOG = """\
664
+ what it does, in order:
665
+ 1. confirms your delivery address (same address confirmation as reorder --
666
+ proposes the first saved address, or pick a different one/type a new one)
667
+ 2. lists delivery types available at that address and asks you to pick one
668
+ -- DeliveryHome (regular home delivery), SelfPickup, and NovaPoshta are
669
+ supported end to end; picking anything else stops here without
670
+ changing anything
671
+ - SelfPickup: lists the nearest pickup branches to your address and
672
+ asks you to pick one
673
+ - NovaPoshta: asks for a city/settlement to search, then an office or
674
+ parcel locker in it
675
+ 3. lists real available timeslots at that delivery type's branch and asks
676
+ you to pick one
677
+ 4. applies the address, delivery type, and timeslot together in a single
678
+ update to your real Silpo cart
679
+ 5. reports which items already in your cart are now unavailable under the
680
+ new delivery context -- purely informational, nothing is removed or
681
+ swapped automatically
682
+
683
+ interactive only -- no flags. an invalid or out-of-range choice at any step
684
+ aborts cleanly without applying anything.
685
+ """
686
+
687
+ _CART_EDIT_EPILOG = """\
688
+ what it does, in order (interactive, no flags):
689
+ 1. lists the items currently in your real cart, numbered
690
+ 2. asks which one to replace
691
+ 3. asks how to find the replacement:
692
+ [1] free-text search -- shows matching candidates (plastic bags are
693
+ never shown as candidates)
694
+ [2] promo alternatives -- reuses `cart promos`'s Similar-Products
695
+ Promo Finder for the specific item being replaced, showing only
696
+ genuinely discounted candidates. If it finds none, falls back to
697
+ the free-text search instead of erroring.
698
+ 4. asks you to confirm the swap
699
+ 5. removes the old item and adds the new one (silpo_remove_cart_products
700
+ then silpo_add_or_update_cart_products -- there's no in-place "update
701
+ this line" call) -- the old item is never removed until the new one is
702
+ confirmed to exist, so a failed/declined swap always leaves the cart
703
+ untouched
704
+
705
+ non-interactive scripting:
706
+ silpo-agent cart edit --replace <old-slug> <new-slug>
707
+ performs the same swap with zero prompts. both arguments are product slugs,
708
+ exactly as printed by `cart`, `deals`, `favorites-deals` and `cart promos` --
709
+ copy one from there rather than constructing it, slugs are generated by Silpo
710
+ and cannot be derived from a product name.
711
+
712
+ <old-slug> is matched against your cart's own lines, locally, with no network
713
+ call. <new-slug> is resolved via silpo_get_product_details, a real per-slug
714
+ lookup that also carries back the companyId/branchId the cart write needs.
715
+
716
+ an old slug not actually in your cart, or a new slug that resolves to
717
+ nothing, errors clearly and leaves the cart untouched.
718
+
719
+ adding a brand-new item, no swap:
720
+ silpo-agent cart edit --add <new-slug> [--quantity NUM]
721
+ adds <new-slug> as a new cart line (quantity 1, or --quantity -- accepts a
722
+ number like 0.5 for weighted products), without
723
+ removing anything. mutually exclusive with --replace; --quantity is only
724
+ valid together with --add. errors instead of touching the cart if
725
+ <new-slug> is already a line in your cart -- rerunning --add would otherwise
726
+ have to guess whether you wanted +N or to leave it alone; use --replace or
727
+ reorder for an item already in your cart.
728
+
729
+ changing the quantity of an item already in your cart:
730
+ silpo-agent cart edit --qty <slug> <num>
731
+ sets that cart line's quantity to <num> -- an absolute set, not a delta (so
732
+ --qty milk 3 always leaves you with 3, regardless of what was there before).
733
+ <num> accepts a number like 0.5 or 1.5 for weighted products. mutually
734
+ exclusive with --replace/--add/--remove. errors instead of touching the cart
735
+ if <slug> isn't already a line in it -- use --add to add it first.
736
+
737
+ removing an item, no replacement:
738
+ silpo-agent cart edit --remove <slug>
739
+ removes <slug>'s cart line, zero prompts, nothing added back. mutually
740
+ exclusive with --replace/--add/--qty. errors instead of touching the cart if
741
+ <slug> isn't actually a line in your cart.
742
+ """
743
+
744
+ _REORDER_EPILOG = """\
745
+ what it does, in order:
746
+ 1. confirms your delivery address (proposes the first saved address;
747
+ you can pick a different one or type a new one)
748
+ 2. looks at your last --last online orders, keeps items that appear in
749
+ at least --threshold share of them ("typical items")
750
+ 3. checks each typical item is still in stock; auto-substitutes when
751
+ there's exactly one replacement, asks you when there's more than one
752
+ (and remembers your answer for next time)
753
+ 4. if --optimize promos was passed: applies any available loyalty
754
+ bonuses to the cart
755
+ 5. warns you before touching a non-empty cart (never silently merges
756
+ or clears it) -- decline aborts with the cart untouched
757
+ 6. if --budget was passed: trims your least-frequent typical items
758
+ until the total fits
759
+ 7. adds the final item set to your real Silpo cart and prints a report
760
+
761
+ it only ever fills the cart -- it never checks out or pays. that step is
762
+ always manual, in the Silpo app or on silpo.ua.
763
+
764
+ examples:
765
+ # typical items = bought in at least half of your last 10 orders
766
+ silpo-agent reorder --last 10 --threshold 0.5
767
+
768
+ # same, but cap the total spend at 1500 UAH
769
+ silpo-agent reorder --last 10 --threshold 0.5 --budget 1500
770
+
771
+ # same, plus apply any available loyalty bonuses to the cart
772
+ silpo-agent reorder --last 10 --threshold 0.5 --optimize promos
773
+
774
+ # non-interactive: auto-confirm every prompt (address, cart warning, substitution picks)
775
+ silpo-agent reorder --last 10 --threshold 0.5 --yes
776
+ """
777
+
778
+
779
+ def main(
780
+ argv: list[str] | None = None, *, client=None, log_store=None, token_store=None, input_fn=None, print_fn=None
781
+ ) -> int:
782
+ input_fn = input_fn or input
783
+ print_fn = print_fn or print
784
+ parser = argparse.ArgumentParser(
785
+ prog="silpo-agent",
786
+ description="Personal CLI wrapper over the Silpo MCP server -- rebuilds your grocery cart from what you "
787
+ "usually buy, instead of re-typing the same list every week.",
788
+ epilog=_TOP_LEVEL_EPILOG,
789
+ formatter_class=argparse.RawDescriptionHelpFormatter,
790
+ )
791
+ parser.add_argument(
792
+ "--version", action="version", version=f"%(prog)s {version('silpo-agent-cli')}"
793
+ )
794
+ subparsers = parser.add_subparsers(dest="command")
795
+ reorder_parser = subparsers.add_parser(
796
+ "reorder",
797
+ help="Rebuild the cart from your typical items",
798
+ description="Rebuild your Silpo cart from the products you buy most consistently, based on your real "
799
+ "online order history. Fills the cart only -- checkout/payment is always a manual step.",
800
+ epilog=_REORDER_EPILOG,
801
+ formatter_class=argparse.RawDescriptionHelpFormatter,
802
+ )
803
+ reorder_parser.add_argument(
804
+ "--last",
805
+ type=int,
806
+ required=True,
807
+ metavar="N",
808
+ help="How many of your most recent online orders to consider. "
809
+ "Errors out (without touching the cart) if you have fewer than N orders.",
810
+ )
811
+ reorder_parser.add_argument(
812
+ "--threshold",
813
+ type=float,
814
+ required=True,
815
+ metavar="0-1",
816
+ help="Minimum share of the --last orders a product must appear in to count as a 'typical item' "
817
+ "(e.g. 0.5 = bought in at least half of them).",
818
+ )
819
+ reorder_parser.add_argument(
820
+ "--budget",
821
+ type=float,
822
+ default=None,
823
+ metavar="UAH",
824
+ help="Optional spend cap in UAH. If the typical-item total exceeds it, the least-frequently-bought "
825
+ "items are trimmed first until it fits. Omit to add everything and just report the total.",
826
+ )
827
+ reorder_parser.add_argument(
828
+ "--optimize",
829
+ choices=["promos"],
830
+ default=None,
831
+ help="Opt-in only -- omitting this flag makes zero promo-related calls. "
832
+ "'promos' applies any available loyalty bonuses to the cart before checkout.",
833
+ )
834
+ reorder_parser.add_argument(
835
+ "--yes",
836
+ "-y",
837
+ action="store_true",
838
+ help="Non-interactive: auto-confirm the proposed delivery address, auto-confirm adding to a "
839
+ "non-empty cart, and auto-pick the first candidate on any substitution with multiple replacements. "
840
+ "Every auto-answered prompt is still printed, and the final report still lists the address used, "
841
+ "substitutions made, and items added -- nothing is decided silently.",
842
+ )
843
+
844
+ smart_cart_parser = subparsers.add_parser(
845
+ "smart-cart",
846
+ help="Rebuild the cart from your typical items, plus discounted favorites and a norm top-up",
847
+ description="Rebuild your Silpo cart from your typical items (same as `reorder`), plus add any of your "
848
+ "favorited products currently on discount that aren't already in the cart, plus a norm top-up: for any "
849
+ "grocery category not covered by the above, propose products sized to --people/--basket-type, gated "
850
+ "behind their own confirmation. Fills the cart only -- checkout/payment is always a manual step.",
851
+ )
852
+ smart_cart_parser.add_argument(
853
+ "--last",
854
+ type=int,
855
+ required=True,
856
+ metavar="N",
857
+ help="How many of your most recent online orders to consider. "
858
+ "Errors out (without touching the cart) if you have fewer than N orders.",
859
+ )
860
+ smart_cart_parser.add_argument(
861
+ "--threshold",
862
+ type=float,
863
+ required=True,
864
+ metavar="0-1",
865
+ help="Minimum share of the --last orders a product must appear in to count as a 'typical item' "
866
+ "(e.g. 0.5 = bought in at least half of them).",
867
+ )
868
+ smart_cart_parser.add_argument(
869
+ "--yes",
870
+ "-y",
871
+ action="store_true",
872
+ help="Non-interactive: auto-confirm the proposed delivery address, auto-confirm adding to a "
873
+ "non-empty cart, auto-pick the first candidate on any substitution with multiple replacements, and "
874
+ "auto-confirm the proposed norm top-up additions.",
875
+ )
876
+ smart_cart_parser.add_argument(
877
+ "--people",
878
+ type=int,
879
+ default=1,
880
+ metavar="N",
881
+ help="Household size used to scale norm top-up quantities (quantity_per_person * N). Must be a "
882
+ "positive integer. Default: 1.",
883
+ )
884
+ smart_cart_parser.add_argument(
885
+ "--basket-type",
886
+ choices=["basic", "eco", "premium"],
887
+ default="eco",
888
+ help="Which household norm dataset to top up uncovered categories from. Default: eco.",
889
+ )
890
+ smart_cart_parser.add_argument(
891
+ "--budget",
892
+ type=float,
893
+ default=None,
894
+ metavar="UAH",
895
+ help="Optional spend cap in UAH. If the combined total exceeds it, items are trimmed by source "
896
+ "priority: norm top-up items first (guesses, not known purchases), then favorited deals, then "
897
+ "typical items as the last resort -- lowest-frequency-first within each source. Omit to add "
898
+ "everything and just report the total.",
899
+ )
900
+
901
+ cart_parser = subparsers.add_parser(
902
+ "cart",
903
+ help="Show your current real cart (read-only); `cart edit`/`cart promos` for more",
904
+ description="Show the current real Silpo cart: items (name/quantity/price/stock), the amount actually "
905
+ "payable (totalAfterDiscounts, never the pre-discount total), any cart validations (stock/timeslot "
906
+ "problems), and your loyalty bonus balance -- the default when no further subcommand is given. "
907
+ "`cart edit` manually replaces one item with another; `cart promos` shows real promo alternatives "
908
+ "for every item.",
909
+ )
910
+ cart_subparsers = cart_parser.add_subparsers(dest="cart_command")
911
+ edit_parser = cart_subparsers.add_parser(
912
+ "edit",
913
+ help="Replace one cart item with another, add a brand-new one, or remove one outright",
914
+ description="Replace one item in your real cart with another -- interactively (list current items, "
915
+ "free-text search a replacement, confirm) or non-interactively via --replace for scripting. --add adds "
916
+ "a new item without removing anything. --remove deletes a line without adding a replacement.",
917
+ epilog=_CART_EDIT_EPILOG,
918
+ formatter_class=argparse.RawDescriptionHelpFormatter,
919
+ )
920
+ edit_group = edit_parser.add_mutually_exclusive_group()
921
+ edit_group.add_argument(
922
+ "--replace",
923
+ nargs=2,
924
+ metavar=("OLD_SLUG", "NEW_SLUG"),
925
+ default=None,
926
+ help="Non-interactive: replace OLD_SLUG with NEW_SLUG, zero prompts. Both are product slugs as printed "
927
+ "by `cart`, `deals`, `favorites-deals` and `cart promos`.",
928
+ )
929
+ edit_group.add_argument(
930
+ "--add",
931
+ metavar="NEW_SLUG",
932
+ default=None,
933
+ help="Non-interactive: add NEW_SLUG as a new cart line (quantity 1, or --quantity), zero prompts, "
934
+ "nothing removed. Errors instead of touching the cart if NEW_SLUG is already in it -- use --replace or "
935
+ "reorder instead.",
936
+ )
937
+ edit_group.add_argument(
938
+ "--qty",
939
+ nargs=2,
940
+ metavar=("SLUG", "NUM"),
941
+ default=None,
942
+ help="Non-interactive: set SLUG's existing cart line quantity to the absolute value NUM (a set, not a "
943
+ "delta), zero prompts. NUM accepts a number, e.g. 0.5 for weighted products sold by kg. Errors instead "
944
+ "of touching the cart if SLUG isn't already a line in it.",
945
+ )
946
+ edit_group.add_argument(
947
+ "--remove",
948
+ metavar="SLUG",
949
+ default=None,
950
+ help="Non-interactive: remove SLUG's cart line, zero prompts, nothing added back. Errors instead of "
951
+ "touching the cart if SLUG isn't actually in it.",
952
+ )
953
+ edit_parser.add_argument(
954
+ "--quantity",
955
+ type=float,
956
+ default=1,
957
+ metavar="NUM",
958
+ help="Quantity for --add (default: 1). Accepts a number, e.g. 0.5 for weighted products sold by kg. "
959
+ "Only valid together with --add.",
960
+ )
961
+ cart_subparsers.add_parser(
962
+ "promos",
963
+ help="Show real promo alternatives for every item currently in your cart (read-only)",
964
+ description="For each item currently in your cart, shows genuinely discounted similar products "
965
+ "(Silpo's own similarity engine, not a name/category guess), ranked by discount size. Purely "
966
+ "informational -- never swaps or modifies anything in your cart. An item with no discounted "
967
+ "alternatives is reported as such, not as an error.",
968
+ )
969
+
970
+ subparsers.add_parser(
971
+ "delivery",
972
+ help="Explicitly set delivery address, delivery type, and timeslot",
973
+ description="Explicitly set your delivery address, delivery type, and timeslot together, in one real "
974
+ "update to your Silpo cart. Supports DeliveryHome, SelfPickup, and NovaPoshta.",
975
+ epilog=_DELIVERY_EPILOG,
976
+ formatter_class=argparse.RawDescriptionHelpFormatter,
977
+ )
978
+
979
+ clear_context_parser = subparsers.add_parser(
980
+ "clear-context",
981
+ help="Wipe your local reorder history, substitution memory, and cached login",
982
+ description="Wipe the local Reorder Log, Substitution Memory, and cached OAuth token after confirmation "
983
+ "-- logs you out. No MCP calls, and your real Silpo cart is never touched.",
984
+ epilog=_CLEAR_CONTEXT_EPILOG,
985
+ formatter_class=argparse.RawDescriptionHelpFormatter,
986
+ )
987
+ clear_context_parser.add_argument(
988
+ "--yes",
989
+ "-y",
990
+ action="store_true",
991
+ help="Non-interactive: skip the confirmation prompt and clear immediately.",
992
+ )
993
+
994
+ subparsers.add_parser(
995
+ "coupons",
996
+ help="List your active loyalty coupons (read-only)",
997
+ description="List your active loyalty coupons with their buying condition, validity dates, and reward. "
998
+ "Read-only -- makes no changes to your cart or account, and never cross-references coupons against "
999
+ "your cart or search results.",
1000
+ )
1001
+
1002
+ subparsers.add_parser(
1003
+ "favorites-deals",
1004
+ help="List your favorited products currently on discount (read-only)",
1005
+ description="Check your own favorites list for items currently discounted (oldPrice > price). "
1006
+ "Read-only -- no matching/heuristic, since it's already your own explicit list.",
1007
+ )
1008
+
1009
+ deals_parser = subparsers.add_parser(
1010
+ "deals",
1011
+ help="Show the best current store-wide discounts (read-only)",
1012
+ description="Scan active promotion categories store-wide and show the biggest current discounts, "
1013
+ "independent of your cart. Read-only -- makes no changes to your cart or account.",
1014
+ )
1015
+ deals_parser.add_argument(
1016
+ "--limit",
1017
+ type=int,
1018
+ default=10,
1019
+ metavar="N",
1020
+ help="How many top deals to show, sorted by discount percentage descending. Default: 10.",
1021
+ )
1022
+ deals_parser.add_argument(
1023
+ "--category",
1024
+ default=None,
1025
+ metavar="NAME",
1026
+ help="Only show deals in this category, e.g. \"Овочі\". Matched by real category title "
1027
+ "(exact match preferred, else the shortest title containing it) -- errors clearly if nothing matches, "
1028
+ "rather than silently showing zero deals.",
1029
+ )
1030
+ deals_parser.add_argument(
1031
+ "--list-categories",
1032
+ action="store_true",
1033
+ help="List every real category title currently available, instead of showing deals -- read-only, "
1034
+ "fetches no deals. Use this to see what to pass to --category.",
1035
+ )
1036
+
1037
+ args = parser.parse_args(argv)
1038
+
1039
+ if args.command is None:
1040
+ return _run_cart(client or MCPClient(), log_store or ReorderLogStore(), input_fn, print_fn)
1041
+
1042
+ if args.command == "reorder":
1043
+ return _run_reorder(
1044
+ args.last,
1045
+ args.threshold,
1046
+ client or MCPClient(),
1047
+ log_store or ReorderLogStore(),
1048
+ budget=args.budget,
1049
+ optimize=args.optimize,
1050
+ yes=args.yes,
1051
+ print_fn=print_fn,
1052
+ )
1053
+
1054
+ if args.command == "smart-cart":
1055
+ return _run_smart_cart(
1056
+ args.last,
1057
+ args.threshold,
1058
+ client or MCPClient(),
1059
+ log_store or ReorderLogStore(),
1060
+ yes=args.yes,
1061
+ print_fn=print_fn,
1062
+ people=args.people,
1063
+ basket_type=args.basket_type,
1064
+ budget=args.budget,
1065
+ )
1066
+
1067
+ if args.command == "cart":
1068
+ if args.cart_command == "edit":
1069
+ if args.quantity != 1 and args.add is None:
1070
+ print_fn("cart edit: --quantity is only valid together with --add")
1071
+ return 1
1072
+ return _run_cart_edit(
1073
+ client or MCPClient(),
1074
+ log_store or ReorderLogStore(),
1075
+ input_fn,
1076
+ print_fn,
1077
+ args.replace,
1078
+ args.add,
1079
+ args.quantity,
1080
+ args.qty,
1081
+ args.remove,
1082
+ )
1083
+ if args.cart_command == "promos":
1084
+ return _run_cart_promos(client or MCPClient(), log_store or ReorderLogStore(), input_fn, print_fn)
1085
+ if args.cart_command is None:
1086
+ return _run_cart(client or MCPClient(), log_store or ReorderLogStore(), input_fn, print_fn)
1087
+ cart_parser.print_help()
1088
+ return 0
1089
+
1090
+ if args.command == "delivery":
1091
+ return _run_delivery(client or MCPClient(), log_store or ReorderLogStore(), input_fn, print_fn)
1092
+
1093
+ if args.command == "clear-context":
1094
+ return _run_clear_context(
1095
+ log_store or ReorderLogStore(), token_store or TokenStore(), input_fn, print_fn, yes=args.yes
1096
+ )
1097
+
1098
+ if args.command == "coupons":
1099
+ return _run_coupons(client or MCPClient())
1100
+
1101
+ if args.command == "favorites-deals":
1102
+ return _run_favorites_deals(client or MCPClient(), log_store or ReorderLogStore(), input_fn, print_fn)
1103
+
1104
+ if args.command == "deals":
1105
+ if args.list_categories:
1106
+ return _run_deals_list_categories(
1107
+ client or MCPClient(), log_store or ReorderLogStore(), input_fn, print_fn
1108
+ )
1109
+ return _run_deals(
1110
+ client or MCPClient(), args.limit, log_store or ReorderLogStore(), input_fn, print_fn, args.category
1111
+ )
1112
+
1113
+ return 0
1114
+
1115
+
1116
+ if __name__ == "__main__":
1117
+ raise SystemExit(main())