-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_data.py
More file actions
1090 lines (968 loc) · 64.1 KB
/
Copy pathgenerate_data.py
File metadata and controls
1090 lines (968 loc) · 64.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Generate test data for all cases in all formats and sizes."""
import json
import random
import yaml
from pathlib import Path
random.seed(42)
DATA_DIR = Path(__file__).parent / "data"
# ── Helpers ────────────────────────────────────────────────────────────────
ADJECTIVES = [
"Pro", "Ultra", "Slim", "Max", "Mini", "Lite", "Plus", "Elite",
"Advanced", "Basic", "Premium", "Essential", "Compact", "Portable",
"Wireless", "Smart", "Digital", "Quick", "Silent", "Dual",
]
PRODUCT_BASES = [
("Mouse", "peripherals", "Ergonomic mouse with adjustable DPI and programmable buttons"),
("Keyboard", "peripherals", "Mechanical keyboard with customizable backlighting"),
("USB-C Hub", "accessories", "Multi-port hub with HDMI and PD charging"),
("Monitor Stand", "accessories", "Height adjustable stand for monitors"),
("Webcam", "peripherals", "HD webcam with auto-focus for video calls"),
("Laptop Sleeve", "accessories", "Protective sleeve with water-resistant coating"),
("Headphones", "audio", "Over-ear headphones with noise cancellation"),
("Microphone", "audio", "Condenser microphone with cardioid pattern"),
("Cable Kit", "accessories", "Cable management set with velcro straps"),
("SSD External", "storage", "Portable SSD with USB-C interface"),
("Charger Pad", "accessories", "Fast wireless charging pad"),
("Office Chair", "furniture", "Ergonomic chair with lumbar support"),
("Desk Lamp", "accessories", "LED lamp with adjustable color temperature"),
("Speaker", "audio", "Portable bluetooth speaker waterproof"),
("Graphics Tablet", "peripherals", "Drawing tablet with pressure sensitivity"),
("NVMe SSD", "storage", "Internal NVMe drive PCIe Gen4"),
("Docking Station", "accessories", "USB-C dock with multiple display outputs"),
("Mousepad", "peripherals", "Extended desk pad with stitched edges"),
("Ring Light", "accessories", "Clip-on light with brightness control"),
("Cable", "accessories", "High-speed data and charging cable"),
("Keyboard Wrist Rest", "peripherals", "Memory foam wrist support"),
("Laptop Stand", "accessories", "Aluminum laptop riser adjustable angle"),
("Webcam Cover", "accessories", "Privacy slider for laptop camera"),
("Screen Protector", "accessories", "Anti-glare matte screen film"),
("USB Flash Drive", "storage", "Compact metal USB 3.2 flash drive"),
("Power Strip", "accessories", "Smart power strip with USB ports and surge protection"),
("Monitor Light Bar", "accessories", "Screen-mounted LED bar for eye comfort"),
("Trackball Mouse", "peripherals", "Ergonomic trackball with thumb control"),
("Audio Interface", "audio", "USB audio interface for recording"),
("Desk Organizer", "accessories", "Multi-slot desktop storage with phone stand"),
]
def generate_products(n):
products = []
for i in range(1, n + 1):
base = PRODUCT_BASES[(i - 1) % len(PRODUCT_BASES)]
adj = ADJECTIVES[(i - 1) % len(ADJECTIVES)]
size_suffix = f" {random.choice(['V2', 'V3', 'X', 'SE', 'Gen2', '2026'])}" if i > len(PRODUCT_BASES) else ""
products.append({
"id": i,
"name": f"{base[0]} {adj}{size_suffix}",
"price": round(random.uniform(9.99, 399.99), 2),
"category": base[1],
"rating": round(random.uniform(3.5, 5.0), 1),
"in_stock": random.random() > 0.15,
"description": base[2],
})
return products
def products_to_json(products):
return json.dumps({"products": products}, indent=2)
def products_to_yaml(products):
return yaml.dump({"products": products}, default_flow_style=False, allow_unicode=True, sort_keys=False)
def products_to_md(products):
lines = ["# Product Catalog", "",
"| ID | Name | Price | Category | Rating | In Stock | Description |",
"|----|------|-------|----------|--------|----------|-------------|"]
for p in products:
stock = "Yes" if p["in_stock"] else "No"
lines.append(f"| {p['id']} | {p['name']} | {p['price']} | {p['category']} | {p['rating']} | {stock} | {p['description']} |")
return "\n".join(lines) + "\n"
def products_to_txt(products):
lines = [f"Product Catalog ({len(products)} items):", ""]
for p in products:
stock = "in stock" if p["in_stock"] else "out of stock"
lines.append(f"{p['id']}. {p['name']} - ${p['price']} - {p['category']} - rating {p['rating']} - {stock} - {p['description']}")
return "\n".join(lines) + "\n"
def products_to_toon(products):
lines = [f"products[{len(products)}]{{id,name,price,category,rating,in_stock,description}}:"]
for p in products:
stock = "true" if p["in_stock"] else "false"
desc = p["description"].replace(",", " ")
lines.append(f"{p['id']},{p['name']},{p['price']},{p['category']},{p['rating']},{stock},{desc}")
return "\n".join(lines) + "\n"
# ── Case 1: System Prompt ─────────────────────────────────────────────────
RULE_TEMPLATES = [
"Never commit .env files or secrets to git",
"Use conventional commit messages (feat:, fix:, docs:, refactor:)",
"All public functions must have docstrings",
"Maximum line length is {n} characters",
"Use type hints for all function parameters and return values",
"Database migrations must be reversible",
"API responses must follow the JSON:API specification",
"Log all errors to stderr, never to stdout",
"Use UTC for all timestamps in the database",
"Never use SELECT * in production queries",
"All user input must be sanitized before database insertion",
"Cache TTL for public pages is {n} seconds",
"Rate limiting: max {n} requests per minute per IP",
"File uploads limited to {n}MB",
"Session timeout after {n} minutes of inactivity",
"CORS allowed origins: {domain}",
"All passwords must be hashed with bcrypt (min {n} rounds)",
"Use connection pooling for database connections (max {n})",
"Enable GZIP compression for responses larger than {n} bytes",
"Health check endpoint must respond within {n}ms",
"Retry failed external API calls up to {n} times with exponential backoff",
"All dates in API responses must use ISO 8601 format",
"Use semantic versioning for all releases",
"Feature flags must have an expiration date",
"Never expose stack traces in production error responses",
"Use prepared statements for all SQL queries",
"WebSocket connections timeout after {n} seconds of inactivity",
"Background jobs must be idempotent",
"Email templates must have both HTML and plain text versions",
"All HTTP redirects must use 301 for permanent and 302 for temporary",
"Static assets must have cache-busting hashes in filenames",
"API pagination defaults to {n} items per page, max {n2}",
"Use structured logging (JSON format) in production",
"All third-party dependencies must be pinned to exact versions",
"Database indexes required for any column used in WHERE clauses",
"Test coverage must be above {n}%",
"CI pipeline must complete within {n} minutes",
"Docker images must use specific tags, never 'latest'",
"Secrets must be stored in environment variables, never in code",
"All API endpoints must validate Content-Type header",
"Use transactions for multi-table writes",
"Error responses must include request_id for tracing",
"Maximum request body size is {n}MB",
"Use HTTP-only secure cookies for session management",
"All external URLs must be validated before redirect",
"Implement circuit breaker for external service calls",
"Database queries must complete within {n}ms (log slow queries)",
"Use HTTPS everywhere, redirect HTTP to HTTPS",
"API versioning via URL prefix (/v1/, /v2/)",
"All cron jobs must have monitoring and alerting",
"Memory limit per container: {n}MB",
"CPU limit per container: {n} cores",
"Log rotation: keep {n} days of logs",
"Backup database daily, retain {n} days",
"Deploy only from main branch, require PR approval",
"All environment-specific config via env vars, not files",
"Use read replicas for heavy read queries",
"Implement graceful shutdown with {n}s drain period",
"All API errors must return proper HTTP status codes",
"Use content security policy headers on all pages",
]
SECTIONS = [
"Code Style", "Security", "Database", "API Design", "Infrastructure",
"Testing", "Deployment", "Monitoring", "Performance", "Authentication",
"Error Handling", "Caching", "Logging", "Configuration", "Documentation",
"CI/CD", "Containers", "Networking", "Data Integrity", "Compliance",
]
def generate_rules(n_rules, n_sections):
sections = {}
rules = RULE_TEMPLATES[:n_rules]
section_names = SECTIONS[:n_sections]
per_section = max(1, n_rules // n_sections)
for i, section in enumerate(section_names):
start = i * per_section
end = start + per_section if i < n_sections - 1 else n_rules
section_rules = []
for r in rules[start:end]:
rule = r.format(n=random.randint(5, 500), n2=random.randint(50, 1000), domain="*.example.com")
section_rules.append(rule)
sections[section] = section_rules
return sections
def rules_to_json(sections):
return json.dumps({"instructions": sections}, indent=2)
def rules_to_yaml(sections):
return yaml.dump({"instructions": sections}, default_flow_style=False, allow_unicode=True, sort_keys=False)
def rules_to_md(sections):
lines = ["# Agent Instructions", ""]
for section, rules in sections.items():
lines.append(f"## {section}")
lines.append("")
for rule in rules:
lines.append(f"- {rule}")
lines.append("")
return "\n".join(lines)
def rules_to_txt(sections):
lines = ["Agent Instructions:", ""]
for section, rules in sections.items():
lines.append(f"{section}:")
for rule in rules:
lines.append(f" - {rule}")
lines.append("")
return "\n".join(lines)
def rules_to_toon(sections):
lines = []
for section, rules in sections.items():
lines.append(f"{section}[{len(rules)}]{{rule}}:")
for rule in rules:
lines.append(rule)
return "\n".join(lines) + "\n"
# ── Case 3: Task List ─────────────────────────────────────────────────────
TASK_NAMES = [
"Set up CI/CD pipeline", "Write unit tests for auth module",
"Design database schema", "Implement user registration",
"Add email verification", "Create admin dashboard",
"Optimize SQL queries", "Set up monitoring alerts",
"Write API documentation", "Implement rate limiting",
"Add search functionality", "Create landing page",
"Set up staging environment", "Implement OAuth login",
"Add payment integration", "Create user settings page",
"Implement file upload", "Add export to CSV",
"Set up error tracking", "Create onboarding flow",
"Implement caching layer", "Add WebSocket support",
"Create mobile responsive layout", "Implement dark mode",
"Add multi-language support", "Create blog engine",
"Implement comment system", "Add notification system",
"Create audit log", "Set up backup automation",
"Implement 2FA", "Add API versioning",
"Create extension marketplace", "Implement coupon system",
"Add analytics dashboard", "Create email templates",
"Implement content moderation", "Add social sharing",
"Create sitemap generator", "Implement SEO meta tags",
"Add performance monitoring", "Create health check endpoint",
"Implement graceful shutdown", "Add request validation",
"Create seed data scripts", "Implement soft delete",
"Add pagination", "Create user roles system",
"Implement inventory tracking", "Add order management",
"Create shipping calculator", "Implement tax calculation",
"Add customer reviews", "Create product recommendations",
"Implement wishlist feature", "Add cart functionality",
"Create checkout flow", "Implement refund system",
"Add subscription billing", "Create loyalty program",
"Implement A/B testing", "Add feature flags",
"Create data migration scripts", "Implement event sourcing",
"Add message queue", "Create background job processor",
"Implement retry logic", "Add circuit breaker",
"Create API gateway", "Implement service mesh",
"Add distributed tracing", "Create chaos testing framework",
"Implement blue-green deployment", "Add canary releases",
"Create rollback automation", "Implement config management",
"Add secret rotation", "Create compliance reports",
"Implement data archival", "Add GDPR tools",
"Create SLA monitoring", "Implement cost optimization",
"Add resource scaling", "Create incident response",
"Implement post-mortem process", "Add on-call rotation",
"Create runbook library", "Implement ChatOps",
"Add deployment notifications", "Create change management",
"Implement infrastructure as code", "Add policy enforcement",
"Create security scanning", "Implement vulnerability management",
"Add dependency updates", "Create release notes automation",
"Implement changelog generation", "Add API deprecation notices",
"Create migration guides", "Implement backward compatibility",
"Add integration tests", "Create load testing suite",
"Implement smoke tests", "Add visual regression tests",
"Create accessibility audit", "Implement performance budget",
"Add bundle size monitoring", "Create lighthouse CI",
"Implement code coverage gates", "Add mutation testing",
"Create contract tests", "Implement chaos engineering",
"Add resilience testing", "Create disaster recovery plan",
"Implement data replication", "Add failover automation",
"Create capacity planning", "Implement auto-scaling",
"Add spot instance management", "Create cost allocation tags",
]
TRACKS = ["Site", "Brand", "ML", "EN", "Outreach", "Admin"]
STATUSES = ["done", "in_progress", "pending"]
ASSIGNEES = ["Ruslan", "AI Assistant", "Contractor"]
def generate_tasks(n):
tasks = []
for i in range(n):
name = TASK_NAMES[i % len(TASK_NAMES)]
suffix = f" (v{i // len(TASK_NAMES) + 1})" if i >= len(TASK_NAMES) else ""
deps = []
if i > 2 and random.random() > 0.6:
deps = [random.randint(1, i) for _ in range(random.randint(1, 2))]
tasks.append({
"id": i + 1,
"name": f"{name}{suffix}",
"track": random.choice(TRACKS),
"status": random.choices(STATUSES, weights=[0.3, 0.2, 0.5])[0],
"priority": random.choice(["high", "medium", "low"]),
"assignee": random.choice(ASSIGNEES),
"depends_on": deps,
})
return tasks
def tasks_to_json(tasks):
return json.dumps({"tasks": tasks}, indent=2)
def tasks_to_yaml(tasks):
return yaml.dump({"tasks": tasks}, default_flow_style=False, allow_unicode=True, sort_keys=False)
def tasks_to_md(tasks):
lines = ["# Project Tasks", "",
"| ID | Name | Track | Status | Priority | Assignee | Depends On |",
"|----|------|-------|--------|----------|----------|------------|"]
for t in tasks:
deps = ", ".join(str(d) for d in t["depends_on"]) if t["depends_on"] else "-"
lines.append(f"| {t['id']} | {t['name']} | {t['track']} | {t['status']} | {t['priority']} | {t['assignee']} | {deps} |")
return "\n".join(lines) + "\n"
def tasks_to_txt(tasks):
lines = [f"Project Tasks ({len(tasks)} items):", ""]
for t in tasks:
deps = f" (depends on: {', '.join(str(d) for d in t['depends_on'])})" if t["depends_on"] else ""
lines.append(f"{t['id']}. [{t['status']}] {t['name']} - {t['track']} - {t['priority']} priority - {t['assignee']}{deps}")
return "\n".join(lines) + "\n"
def tasks_to_toon(tasks):
lines = [f"tasks[{len(tasks)}]{{id,name,track,status,priority,assignee,depends_on}}:"]
for t in tasks:
deps = "|".join(str(d) for d in t["depends_on"]) if t["depends_on"] else ""
lines.append(f"{t['id']},{t['name']},{t['track']},{t['status']},{t['priority']},{t['assignee']},{deps}")
return "\n".join(lines) + "\n"
# ── Case 4: Business Rules ────────────────────────────────────────────────
RULE_DEFS = [
{"id": "R1", "condition": "order.total > 100", "action": "apply 10% discount", "priority": 1},
{"id": "R2", "condition": "order.category == 'electronics' AND order.total > 500", "action": "free shipping", "priority": 2},
{"id": "R3", "condition": "customer.is_vip == true", "action": "apply additional 5% discount", "priority": 3},
{"id": "R4", "condition": "order.shipping_country NOT IN ['ES', 'PT', 'FR', 'DE', 'IT']", "action": "add 15 EUR surcharge", "priority": 1},
{"id": "R5", "condition": "coupon_code == 'LAUNCH2026'", "action": "free shipping AND 20% discount (max 50 EUR)", "priority": 0},
{"id": "R6", "condition": "order.items_count > 5", "action": "apply 5% bulk discount", "priority": 4},
{"id": "R7", "condition": "order.payment_method == 'bank_transfer'", "action": "apply 2% payment discount", "priority": 5},
{"id": "R8", "condition": "order.total < 25", "action": "add 4.99 EUR handling fee", "priority": 1},
{"id": "R9", "condition": "customer.orders_count > 10", "action": "loyalty bonus: free gift wrap", "priority": 6},
{"id": "R10", "condition": "order.contains_hazardous == true", "action": "add 25 EUR hazmat shipping", "priority": 0},
{"id": "R11", "condition": "order.weight_kg > 30", "action": "add 12 EUR heavy item surcharge", "priority": 2},
{"id": "R12", "condition": "order.is_gift == true", "action": "add gift wrapping 3.99 EUR", "priority": 7},
{"id": "R13", "condition": "order.delivery_speed == 'express'", "action": "add 9.99 EUR express fee", "priority": 1},
{"id": "R14", "condition": "customer.account_age_days < 30", "action": "require payment verification", "priority": 0},
{"id": "R15", "condition": "order.total > 1000", "action": "apply 15% discount, assign account manager", "priority": 1},
{"id": "R16", "condition": "order.currency != 'EUR'", "action": "add 2.5% currency conversion fee", "priority": 2},
{"id": "R17", "condition": "order.shipping_country == 'ES' AND order.total > 50", "action": "free shipping within Spain", "priority": 3},
{"id": "R18", "condition": "order.has_subscription == true", "action": "apply 10% subscription discount", "priority": 2},
{"id": "R19", "condition": "order.time_of_day BETWEEN '22:00' AND '06:00'", "action": "apply 5% night owl discount", "priority": 8},
{"id": "R20", "condition": "customer.referred_by IS NOT NULL", "action": "apply 10 EUR referral credit", "priority": 4},
{"id": "R21", "condition": "order.items_count == 1 AND order.total < 15", "action": "suggest bundle: add related item for 20% off", "priority": 9},
{"id": "R22", "condition": "order.shipping_method == 'pickup'", "action": "waive shipping, apply 3% pickup discount", "priority": 3},
{"id": "R23", "condition": "customer.birthday_month == current_month", "action": "apply 15% birthday discount (max 30 EUR)", "priority": 5},
{"id": "R24", "condition": "order.category == 'furniture' AND order.shipping_country != 'ES'", "action": "add 45 EUR international furniture shipping", "priority": 1},
{"id": "R25", "condition": "order.total > 200 AND customer.is_vip == false", "action": "offer VIP upgrade", "priority": 10},
{"id": "R26", "condition": "order.coupon_stacking == true AND order.coupons_count > 1", "action": "reject: max 1 coupon per order", "priority": 0},
{"id": "R27", "condition": "order.is_preorder == true", "action": "charge 50% now, 50% on shipping", "priority": 1},
{"id": "R28", "condition": "order.total > 75 AND order.shipping_country IN ['ES', 'PT']", "action": "free standard shipping Iberia", "priority": 3},
{"id": "R29", "condition": "customer.failed_payments > 2", "action": "require prepayment only", "priority": 0},
{"id": "R30", "condition": "order.contains_fragile == true", "action": "add 6.99 EUR fragile handling", "priority": 2},
{"id": "R31", "condition": "order.return_rate > 0.3", "action": "flag for manual review", "priority": 0},
{"id": "R32", "condition": "order.total > 500 AND order.payment_method == 'credit_card'", "action": "apply 3D Secure verification", "priority": 0},
{"id": "R33", "condition": "order.items.any(item.stock < 5)", "action": "show low stock warning", "priority": 7},
{"id": "R34", "condition": "order.scheduled_delivery IS NOT NULL", "action": "add 4.99 EUR scheduled delivery fee", "priority": 3},
{"id": "R35", "condition": "customer.language == 'es' AND order.shipping_country == 'ES'", "action": "use Spanish invoice template", "priority": 8},
{"id": "R36", "condition": "order.insurance_requested == true", "action": "add 2% of order total as insurance", "priority": 4},
{"id": "R37", "condition": "order.total > 150 AND order.category == 'audio'", "action": "include free cable set", "priority": 6},
{"id": "R38", "condition": "customer.is_wholesale == true", "action": "apply wholesale pricing tier", "priority": 1},
{"id": "R39", "condition": "order.eco_packaging == true", "action": "waive packaging fee, add eco badge", "priority": 7},
{"id": "R40", "condition": "order.shipping_country IN ['UK', 'CH', 'NO']", "action": "add customs declaration, estimate duties", "priority": 2},
{"id": "R41", "condition": "customer.cart_abandoned_count > 3", "action": "offer 10% recovery discount via email", "priority": 9},
{"id": "R42", "condition": "order.contains_digital_only == true", "action": "skip shipping, instant delivery", "priority": 1},
{"id": "R43", "condition": "order.total > 50 AND order.is_first_order == true", "action": "apply 10% first order discount", "priority": 3},
{"id": "R44", "condition": "order.delivery_address.is_PO_box == true", "action": "reject express shipping option", "priority": 2},
{"id": "R45", "condition": "order.items_count > 20", "action": "split into multiple shipments", "priority": 1},
{"id": "R46", "condition": "customer.tier == 'gold'", "action": "priority processing, 1-day handling", "priority": 3},
{"id": "R47", "condition": "order.includes_installation == true", "action": "add 49.99 EUR installation service", "priority": 4},
{"id": "R48", "condition": "order.total > 300 AND order.payment_method == 'klarna'", "action": "offer 3-month installment plan", "priority": 5},
{"id": "R49", "condition": "order.category == 'storage' AND order.items_count > 3", "action": "apply storage bundle: 20% off", "priority": 4},
{"id": "R50", "condition": "customer.subscribed_newsletter == false", "action": "show newsletter popup with 5% discount incentive", "priority": 10},
]
def generate_rules_biz(n_rules, n_orders):
rules = RULE_DEFS[:n_rules]
orders = []
countries = ["ES", "PT", "FR", "DE", "IT", "UK", "US", "PL", "NL", "CH", "NO"]
categories = ["electronics", "peripherals", "audio", "furniture", "storage", "accessories"]
payments = ["credit_card", "bank_transfer", "paypal", "klarna"]
for i in range(1, n_orders + 1):
orders.append({
"order_id": f"ORD-{1000 + i}",
"customer": {
"is_vip": random.random() > 0.8,
"orders_count": random.randint(0, 20),
"account_age_days": random.randint(1, 365),
},
"items_count": random.randint(1, 15),
"total": round(random.uniform(10, 800), 2),
"category": random.choice(categories),
"shipping_country": random.choice(countries),
"payment_method": random.choice(payments),
"coupon_code": random.choice([None, None, None, "LAUNCH2026", "SAVE10"]),
})
return {"rules": rules, "orders": orders}
def biz_to_json(data):
return json.dumps(data, indent=2)
def biz_to_yaml(data):
return yaml.dump(data, default_flow_style=False, allow_unicode=True, sort_keys=False)
def biz_to_md(data):
lines = ["# Business Rules", ""]
lines.append("## Rules")
lines.append("")
lines.append("| ID | Condition | Action | Priority |")
lines.append("|----|-----------|--------|----------|")
for r in data["rules"]:
lines.append(f"| {r['id']} | {r['condition']} | {r['action']} | {r['priority']} |")
lines.append("")
lines.append("## Orders to Process")
lines.append("")
lines.append("| Order ID | VIP | Orders | Age(d) | Items | Total | Category | Country | Payment | Coupon |")
lines.append("|----------|-----|--------|--------|-------|-------|----------|---------|---------|--------|")
for o in data["orders"]:
c = o["customer"]
coupon = o["coupon_code"] or "-"
lines.append(f"| {o['order_id']} | {c['is_vip']} | {c['orders_count']} | {c['account_age_days']} | {o['items_count']} | {o['total']} | {o['category']} | {o['shipping_country']} | {o['payment_method']} | {coupon} |")
return "\n".join(lines) + "\n"
def biz_to_txt(data):
lines = ["Business Rules:", ""]
for r in data["rules"]:
lines.append(f" {r['id']}: IF {r['condition']} THEN {r['action']} (priority: {r['priority']})")
lines.append("")
lines.append("Orders to Process:")
lines.append("")
for o in data["orders"]:
c = o["customer"]
coupon = f", coupon: {o['coupon_code']}" if o["coupon_code"] else ""
lines.append(f" {o['order_id']}: {o['items_count']} items, ${o['total']}, {o['category']}, ship to {o['shipping_country']}, pay via {o['payment_method']}{coupon} (customer: VIP={c['is_vip']}, {c['orders_count']} orders, {c['account_age_days']}d old)")
return "\n".join(lines) + "\n"
def biz_to_toon(data):
lines = [f"rules[{len(data['rules'])}]{{id,condition,action,priority}}:"]
for r in data["rules"]:
cond = r["condition"].replace(",", ";")
action = r["action"].replace(",", ";")
lines.append(f"{r['id']},{cond},{action},{r['priority']}")
lines.append("")
lines.append(f"orders[{len(data['orders'])}]{{order_id,is_vip,orders_count,account_age_days,items_count,total,category,shipping_country,payment_method,coupon_code}}:")
for o in data["orders"]:
c = o["customer"]
coupon = o["coupon_code"] or ""
lines.append(f"{o['order_id']},{c['is_vip']},{c['orders_count']},{c['account_age_days']},{o['items_count']},{o['total']},{o['category']},{o['shipping_country']},{o['payment_method']},{coupon}")
return "\n".join(lines) + "\n"
# ── Write helpers ──────────────────────────────────────────────────────────
def write_case(case_dir, size_label, converters, data):
"""Write data in all 5 formats."""
case_dir.mkdir(parents=True, exist_ok=True)
for ext, converter in converters.items():
path = case_dir / f"input-{size_label}.{ext}"
path.write_text(converter(data))
# ── Main ───────────────────────────────────────────────────────────────────
def main():
print("Generating test data...\n")
# Case 1: System Prompt
case1 = DATA_DIR / "case1-instructions"
converters1 = {"json": rules_to_json, "yaml": rules_to_yaml, "md": rules_to_md, "txt": rules_to_txt, "toon": rules_to_toon}
for label, (n_rules, n_sections) in {"s": (10, 5), "m": (30, 12), "l": (60, 20)}.items():
data = generate_rules(n_rules, n_sections)
write_case(case1, label, converters1, data)
print(f" case1-instructions {label}: {n_rules} rules, {n_sections} sections")
# Case 2: Product Catalog
case2 = DATA_DIR / "case2-products"
converters2 = {"json": products_to_json, "yaml": products_to_yaml, "md": products_to_md, "txt": products_to_txt, "toon": products_to_toon}
for label, n in {"s": 20, "m": 100, "l": 200}.items():
data = generate_products(n)
write_case(case2, label, converters2, data)
print(f" case2-products {label}: {n} products")
# Case 3: Task List
case3 = DATA_DIR / "case3-tasks"
converters3 = {"json": tasks_to_json, "yaml": tasks_to_yaml, "md": tasks_to_md, "txt": tasks_to_txt, "toon": tasks_to_toon}
for label, n in {"s": 15, "m": 50, "l": 120}.items():
data = generate_tasks(n)
write_case(case3, label, converters3, data)
print(f" case3-tasks {label}: {n} tasks")
# Case 4: Business Rules
case4 = DATA_DIR / "case4-rules"
converters4 = {"json": biz_to_json, "yaml": biz_to_yaml, "md": biz_to_md, "txt": biz_to_txt, "toon": biz_to_toon}
for label, (n_rules, n_orders) in {"s": (8, 5), "m": (25, 10), "l": (50, 20)}.items():
data = generate_rules_biz(n_rules, n_orders)
write_case(case4, label, converters4, data)
print(f" case4-rules {label}: {n_rules} rules, {n_orders} orders")
# Case 5: Few-shot Classification
case5 = DATA_DIR / "case5-fewshot"
for label, (n_examples, n_test) in {"s": (5, 5), "m": (15, 10), "l": (40, 20)}.items():
data = generate_fewshot(n_examples, n_test)
write_case(case5, label, {
"json": fewshot_to_json, "yaml": fewshot_to_yaml,
"md": fewshot_to_md, "txt": fewshot_to_txt, "toon": fewshot_to_toon,
}, data)
print(f" case5-fewshot {label}: {n_examples} examples, {n_test} test")
# Case 6: Nested Hierarchy
case6 = DATA_DIR / "case6-hierarchy"
for label, (n_dept, n_team_per, n_member_per) in {"s": (2, 2, 3), "m": (5, 3, 4), "l": (10, 3, 5)}.items():
data = generate_hierarchy(n_dept, n_team_per, n_member_per)
write_case(case6, label, {
"json": hierarchy_to_json, "yaml": hierarchy_to_yaml,
"md": hierarchy_to_md, "txt": hierarchy_to_txt, "toon": hierarchy_to_toon,
}, data)
total = n_dept * n_team_per * n_member_per
print(f" case6-hierarchy {label}: {n_dept} depts, {n_dept*n_team_per} teams, {total} people")
# Case 7: API Documentation
case7 = DATA_DIR / "case7-api-docs"
for label, n in {"s": 5, "m": 15, "l": 30}.items():
data = generate_api_docs(n)
write_case(case7, label, {
"json": api_to_json, "yaml": api_to_yaml,
"md": api_to_md, "txt": api_to_txt, "toon": api_to_toon,
}, data)
print(f" case7-api-docs {label}: {n} endpoints")
# Case 8: Output Format (just a prompt, same for all formats)
case8 = DATA_DIR / "case8-output"
for label, n in {"s": 10, "m": 50, "l": 100}.items():
prompt = f"List {n} European countries. For each provide: name, capital, population (approximate), EU member (yes/no). Return the data as a structured list."
for ext in ["json", "yaml", "md", "txt", "toon"]:
(case8 / f"input-{label}.{ext}").write_text(prompt + f"\n\nReturn the result in {ext.upper()} format.\n")
print(f" case8-output {label}: {n} countries")
print(f"\nDone. All cases generated.")
# ── Case 5: Few-shot Classification ───────────────────────────────────────
TICKET_TEMPLATES = {
"billing": [
"I was charged twice for my last order #{id}. Please refund the duplicate payment.",
"My invoice shows incorrect tax amount. Order total should be ${amount} not ${amount2}.",
"I need to update my payment method. My card ending in {card} expired.",
"When will I receive the refund for returned item? It's been {days} days.",
"I can't download my invoice PDF for order #{id}. The link is broken.",
"My subscription was renewed but I cancelled it {days} days ago.",
"The discount code {code} wasn't applied to my order #{id}.",
"I need a receipt for tax purposes for orders from last {period}.",
"My account shows a negative balance of -${amount}. This seems wrong.",
"The currency conversion fee seems too high on my international order.",
"I was promised free shipping but got charged ${amount} for delivery.",
"Can I split payment between two credit cards for a large order?",
"My payment failed but the order shows as confirmed. What happened?",
"I need to change the billing address on my upcoming subscription renewal.",
"The promotional price I saw isn't reflected in my cart total.",
"I received a collections notice but I already paid invoice #{id}.",
"My loyalty points weren't credited for purchase #{id} made {days} days ago.",
"I need an itemized breakdown of charges for expense reporting.",
"The auto-pay feature charged my old card instead of the updated one.",
"I'm being charged sales tax but my organization is tax-exempt.",
],
"technical": [
"The website is extremely slow. Pages take over {seconds}s to load.",
"I get a 500 error when trying to checkout. This has been happening for {days} days.",
"The search function returns no results even for products I know exist.",
"Images are not loading on the product pages. I see broken image icons.",
"I can't log in. It says 'invalid credentials' but my password is correct.",
"The mobile app crashes every time I try to open my cart.",
"Two-factor authentication code is not being sent to my phone.",
"The product comparison feature shows wrong specifications.",
"My browser shows a security warning when accessing the checkout page.",
"The API endpoint /v2/orders returns 403 even with valid auth token.",
"File upload fails for any file larger than {size}MB. The limit should be higher.",
"The real-time inventory shows items as available but checkout says out of stock.",
"Push notifications stopped working after the last app update.",
"The export to CSV feature produces corrupted files with wrong encoding.",
"My saved filters reset every time I navigate away from the search page.",
"The webhook is not firing for order.completed events since yesterday.",
"SSL certificate warning appears intermittently on the admin panel.",
"The date picker component shows wrong timezone. I'm in {timezone}.",
"Auto-complete in the address field suggests locations in wrong country.",
"The integration with our ERP system broke after your API update v2.3.",
],
"feature_request": [
"It would be great to have bulk export of order data to Excel format.",
"Can you add dark mode? Working late hours with bright screen is painful.",
"Please add support for Apple Pay at checkout.",
"I'd love to see a wishlist sharing feature for gift registries.",
"Could you add multi-currency display so I can see prices in {currency}?",
"We need an API endpoint for batch updating inventory levels.",
"It would help to have automated reorder suggestions based on purchase history.",
"Can you add integration with {service} for shipping rate comparison?",
"Please consider adding scheduled reports delivered via email.",
"A customer segmentation tool would be very useful for our marketing.",
"We'd like to offer product bundles with dynamic pricing.",
"Can you add support for gift cards with custom amounts?",
"It would be nice to have order status webhooks in real-time.",
"Please add a sandbox/staging environment for testing integrations.",
"We need role-based access control for team members in the admin.",
"Could you add barcode scanning for inventory management?",
"A built-in A/B testing tool for product pages would be valuable.",
"Please add support for recurring/subscription orders.",
"We'd love to have AI-powered product recommendations on the homepage.",
"Can you add print-friendly invoice templates that we can customize?",
],
"bug_report": [
"Clicking 'Add to Cart' sometimes adds the item twice. Reproducible on Chrome {version}.",
"The order total doesn't update when I change quantity. I have to refresh the page.",
"The email confirmation shows wrong delivery date. It says {date} instead of the actual date.",
"Product reviews appear under the wrong product after using the search filter.",
"The 'Remember Me' checkbox doesn't work. I have to log in every session.",
"Sorting by price shows items in wrong order when prices have decimals.",
"The breadcrumb navigation breaks when category name contains special characters.",
"Deleting an item from cart also removes the applied coupon code.",
"The stock counter shows negative numbers (-{count}) for some products.",
"Order confirmation email contains HTML tags instead of formatted text.",
"The related products section shows items that are discontinued.",
"Applying filter 'Price: Low to High' then 'In Stock Only' resets the price sort.",
"The shipping calculator returns $0 for international orders to {country}.",
"User profile update saves the name but silently drops the phone number.",
"The notification badge count doesn't decrease after reading notifications.",
"Pagination breaks on page 4+ when combined with category filter.",
"The print button on order details page prints a blank page in Firefox.",
"Search autocomplete suggests products that are not available in my region.",
"The 'Track Order' link in email leads to a 404 page for orders older than 30 days.",
"Password reset email contains a link that expires before it can be clicked ({seconds}s).",
],
"general": [
"What are your business hours for phone support?",
"Do you ship to {country}? I couldn't find shipping info on the website.",
"How long does standard delivery take within the EU?",
"What's your return policy for electronic items?",
"Can I visit your showroom? Where is it located?",
"Do you offer student discounts?",
"I'd like to partner with your company for affiliate marketing.",
"How do I delete my account and all associated data?",
"Are your products covered by manufacturer warranty?",
"Do you have a physical catalog I can request?",
"What payment methods do you accept besides credit cards?",
"How can I track my order #{id}?",
"Is it possible to change my delivery address after placing the order?",
"Do you offer corporate/wholesale pricing for large orders?",
"What's the difference between Standard and Premium membership?",
"Can I schedule a product demo with your sales team?",
"How do I unsubscribe from your marketing emails?",
"Do you have accessibility features for users with disabilities?",
"What certifications do your products have (CE, FCC, etc.)?",
"How do I contact your data protection officer regarding GDPR?",
],
}
def generate_fewshot(n_examples, n_test):
categories = list(TICKET_TEMPLATES.keys())
examples = []
test_items = []
for i in range(n_examples):
cat = categories[i % len(categories)]
templates = TICKET_TEMPLATES[cat]
text = templates[i % len(templates)].format(
id=random.randint(1000, 9999), amount=random.randint(10, 500),
amount2=random.randint(10, 500), card=random.randint(1000, 9999),
days=random.randint(1, 30), code=f"SAVE{random.randint(10,50)}",
period="quarter", seconds=random.randint(5, 30),
size=random.randint(5, 50), timezone="CET",
currency="GBP", service="ShipStation", version="120",
date="2026-04-20", count=random.randint(1, 10),
country="Brazil",
)
examples.append({"text": text, "category": cat})
for i in range(n_test):
cat = categories[i % len(categories)]
templates = TICKET_TEMPLATES[cat]
idx = (n_examples + i) % len(templates)
text = templates[idx].format(
id=random.randint(1000, 9999), amount=random.randint(10, 500),
amount2=random.randint(10, 500), card=random.randint(1000, 9999),
days=random.randint(1, 30), code=f"DEAL{random.randint(10,50)}",
period="month", seconds=random.randint(5, 30),
size=random.randint(5, 50), timezone="PST",
currency="JPY", service="Zapier", version="121",
date="2026-05-01", count=random.randint(1, 10),
country="Japan",
)
test_items.append({"text": text, "category": cat})
return {"examples": examples, "test": test_items}
def fewshot_to_json(data):
return json.dumps(data, indent=2)
def fewshot_to_yaml(data):
return yaml.dump(data, default_flow_style=False, allow_unicode=True, sort_keys=False)
def fewshot_to_md(data):
lines = ["# Support Ticket Classification", "", "## Examples", ""]
lines.append("| Text | Category |")
lines.append("|------|----------|")
for ex in data["examples"]:
lines.append(f"| {ex['text']} | {ex['category']} |")
lines.append("")
lines.append("## Classify These Tickets")
lines.append("")
for i, t in enumerate(data["test"], 1):
lines.append(f"{i}. {t['text']}")
return "\n".join(lines) + "\n"
def fewshot_to_txt(data):
lines = ["Support Ticket Classification", "", "Examples:", ""]
for ex in data["examples"]:
lines.append(f" Text: {ex['text']}")
lines.append(f" Category: {ex['category']}")
lines.append("")
lines.append("Classify these tickets:")
lines.append("")
for i, t in enumerate(data["test"], 1):
lines.append(f" {i}. {t['text']}")
return "\n".join(lines) + "\n"
def fewshot_to_toon(data):
lines = [f"examples[{len(data['examples'])}]{{text,category}}:"]
for ex in data["examples"]:
text = ex["text"].replace(",", ";")
lines.append(f"{text},{ex['category']}")
lines.append("")
lines.append(f"test[{len(data['test'])}]{{text}}:")
for t in data["test"]:
lines.append(t["text"].replace(",", ";"))
return "\n".join(lines) + "\n"
# ── Case 6: Nested Hierarchy ──────────────────────────────────────────────
DEPT_NAMES = ["Engineering", "Marketing", "Sales", "Operations", "Finance",
"Product", "Design", "Data Science", "Security", "Platform"]
TEAM_PREFIXES = ["Core", "Growth", "Platform", "Mobile", "API", "Frontend",
"Backend", "Infrastructure", "Analytics", "ML", "QA",
"DevOps", "Content", "SEO", "Partnerships", "Enterprise",
"SMB", "Support", "Enablement", "Strategy"]
FIRST_NAMES = ["Alex", "Sam", "Jordan", "Taylor", "Casey", "Morgan", "Jamie",
"Quinn", "Avery", "Riley", "Skyler", "Dakota", "Reese", "Hayden",
"Cameron", "Drew", "Finley", "Rowan", "Sage", "Emerson",
"Blake", "Charlie", "Frankie", "Harley", "Jules", "Kai",
"Lane", "Noel", "Parker", "Robin", "Shay", "Terry", "Val"]
SKILLS = ["Python", "JavaScript", "TypeScript", "Go", "Rust", "Java", "PHP",
"SQL", "React", "Vue", "Docker", "Kubernetes", "AWS", "GCP",
"Machine Learning", "Data Analysis", "Product Management",
"UI/UX Design", "Technical Writing", "Project Management"]
ROLES = ["Engineer", "Senior Engineer", "Team Lead", "Manager", "Analyst",
"Designer", "Architect", "Specialist", "Coordinator"]
def generate_hierarchy(n_depts, n_teams_per_dept, n_members_per_team):
departments = []
member_id = 1
for d in range(n_depts):
dept_name = DEPT_NAMES[d % len(DEPT_NAMES)]
teams = []
for t in range(n_teams_per_dept):
team_name = f"{TEAM_PREFIXES[(d * n_teams_per_dept + t) % len(TEAM_PREFIXES)]} Team"
members = []
for m in range(n_members_per_team):
name = FIRST_NAMES[(member_id - 1) % len(FIRST_NAMES)]
n_skills = random.randint(2, 5)
member_skills = random.sample(SKILLS, min(n_skills, len(SKILLS)))
is_lead = (m == 0)
members.append({
"id": member_id,
"name": name,
"role": "Team Lead" if is_lead else random.choice(ROLES),
"skills": member_skills,
})
member_id += 1
teams.append({"name": team_name, "members": members})
departments.append({"name": dept_name, "teams": teams})
return {"organization": departments}
def hierarchy_to_json(data):
return json.dumps(data, indent=2)
def hierarchy_to_yaml(data):
return yaml.dump(data, default_flow_style=False, allow_unicode=True, sort_keys=False)
def hierarchy_to_md(data):
lines = ["# Organization Structure", ""]
for dept in data["organization"]:
lines.append(f"## {dept['name']}")
lines.append("")
for team in dept["teams"]:
lines.append(f"### {team['name']}")
lines.append("")
lines.append("| ID | Name | Role | Skills |")
lines.append("|----|------|------|--------|")
for m in team["members"]:
skills = ", ".join(m["skills"])
lines.append(f"| {m['id']} | {m['name']} | {m['role']} | {skills} |")
lines.append("")
return "\n".join(lines)
def hierarchy_to_txt(data):
lines = ["Organization Structure:", ""]
for dept in data["organization"]:
lines.append(f"{dept['name']}:")
for team in dept["teams"]:
lines.append(f" {team['name']}:")
for m in team["members"]:
skills = ", ".join(m["skills"])
lines.append(f" {m['id']}. {m['name']} ({m['role']}) - skills: {skills}")
lines.append("")
return "\n".join(lines)
def hierarchy_to_toon(data):
lines = []
for dept in data["organization"]:
lines.append(f"{dept['name']}:")
for team in dept["teams"]:
members = team["members"]
lines.append(f" {team['name']}[{len(members)}]{{id,name,role,skills}}:")
for m in members:
skills = "|".join(m["skills"])
lines.append(f" {m['id']},{m['name']},{m['role']},{skills}")
return "\n".join(lines) + "\n"
# ── Case 7: API Documentation ─────────────────────────────────────────────
API_ENDPOINTS = [
{"method": "GET", "path": "/api/v2/products", "desc": "List all products with pagination", "params": [
{"name": "page", "type": "integer", "required": False, "default": 1, "desc": "Page number"},
{"name": "per_page", "type": "integer", "required": False, "default": 20, "desc": "Items per page (max 100)"},
{"name": "category", "type": "string", "required": False, "default": None, "desc": "Filter by category slug"},
{"name": "sort", "type": "string", "required": False, "default": "created_at", "desc": "Sort field: price, rating, created_at"},
], "responses": {"200": "List of products", "400": "Invalid parameters", "401": "Unauthorized"}},
{"method": "GET", "path": "/api/v2/products/{id}", "desc": "Get single product by ID", "params": [
{"name": "id", "type": "integer", "required": True, "default": None, "desc": "Product ID"},
], "responses": {"200": "Product object", "404": "Product not found"}},
{"method": "POST", "path": "/api/v2/orders", "desc": "Create a new order", "params": [
{"name": "items", "type": "array", "required": True, "default": None, "desc": "Array of {product_id, quantity}"},
{"name": "shipping_address", "type": "object", "required": True, "default": None, "desc": "Address with street, city, country, postal_code"},
{"name": "payment_method", "type": "string", "required": True, "default": None, "desc": "Payment method: credit_card, paypal, bank_transfer"},
{"name": "coupon_code", "type": "string", "required": False, "default": None, "desc": "Optional coupon code"},
{"name": "notes", "type": "string", "required": False, "default": None, "desc": "Order notes"},
], "responses": {"201": "Order created", "400": "Validation error", "422": "Unprocessable: out of stock or invalid coupon"}},
{"method": "GET", "path": "/api/v2/orders/{id}", "desc": "Get order details", "params": [
{"name": "id", "type": "integer", "required": True, "default": None, "desc": "Order ID"},
], "responses": {"200": "Order with items and status", "403": "Not your order", "404": "Order not found"}},
{"method": "PATCH", "path": "/api/v2/orders/{id}", "desc": "Update order (before shipping)", "params": [
{"name": "id", "type": "integer", "required": True, "default": None, "desc": "Order ID"},
{"name": "shipping_address", "type": "object", "required": False, "default": None, "desc": "Updated address"},
{"name": "notes", "type": "string", "required": False, "default": None, "desc": "Updated notes"},
], "responses": {"200": "Updated order", "400": "Order already shipped", "404": "Order not found"}},
{"method": "DELETE", "path": "/api/v2/orders/{id}", "desc": "Cancel order (before shipping)", "params": [
{"name": "id", "type": "integer", "required": True, "default": None, "desc": "Order ID"},
{"name": "reason", "type": "string", "required": True, "default": None, "desc": "Cancellation reason"},
], "responses": {"200": "Order cancelled", "400": "Cannot cancel shipped order", "404": "Order not found"}},
{"method": "GET", "path": "/api/v2/customers/me", "desc": "Get current customer profile", "params": [], "responses": {"200": "Customer profile", "401": "Unauthorized"}},
{"method": "PATCH", "path": "/api/v2/customers/me", "desc": "Update customer profile", "params": [
{"name": "name", "type": "string", "required": False, "default": None, "desc": "Full name"},
{"name": "email", "type": "string", "required": False, "default": None, "desc": "Email address"},
{"name": "phone", "type": "string", "required": False, "default": None, "desc": "Phone number"},
{"name": "language", "type": "string", "required": False, "default": None, "desc": "Preferred language (en, es, de)"},
], "responses": {"200": "Updated profile", "400": "Validation error", "409": "Email already exists"}},
{"method": "POST", "path": "/api/v2/auth/login", "desc": "Authenticate and get access token", "params": [
{"name": "email", "type": "string", "required": True, "default": None, "desc": "Account email"},
{"name": "password", "type": "string", "required": True, "default": None, "desc": "Account password"},
], "responses": {"200": "Access token + refresh token", "401": "Invalid credentials", "429": "Too many attempts"}},
{"method": "POST", "path": "/api/v2/auth/refresh", "desc": "Refresh access token", "params": [
{"name": "refresh_token", "type": "string", "required": True, "default": None, "desc": "Valid refresh token"},
], "responses": {"200": "New access token", "401": "Invalid or expired refresh token"}},
{"method": "GET", "path": "/api/v2/categories", "desc": "List all product categories", "params": [
{"name": "include_empty", "type": "boolean", "required": False, "default": False, "desc": "Include categories with 0 products"},
], "responses": {"200": "List of categories with product counts"}},
{"method": "POST", "path": "/api/v2/reviews", "desc": "Submit a product review", "params": [
{"name": "product_id", "type": "integer", "required": True, "default": None, "desc": "Product to review"},
{"name": "rating", "type": "integer", "required": True, "default": None, "desc": "Rating 1-5"},
{"name": "title", "type": "string", "required": True, "default": None, "desc": "Review title"},
{"name": "body", "type": "string", "required": True, "default": None, "desc": "Review text"},
], "responses": {"201": "Review created (pending moderation)", "400": "Validation error", "409": "Already reviewed this product"}},
{"method": "GET", "path": "/api/v2/reviews", "desc": "List reviews for a product", "params": [
{"name": "product_id", "type": "integer", "required": True, "default": None, "desc": "Product ID"},
{"name": "sort", "type": "string", "required": False, "default": "newest", "desc": "Sort: newest, highest, lowest, helpful"},
{"name": "page", "type": "integer", "required": False, "default": 1, "desc": "Page number"},
], "responses": {"200": "List of approved reviews", "404": "Product not found"}},
{"method": "POST", "path": "/api/v2/cart/items", "desc": "Add item to cart", "params": [
{"name": "product_id", "type": "integer", "required": True, "default": None, "desc": "Product ID"},
{"name": "quantity", "type": "integer", "required": False, "default": 1, "desc": "Quantity to add"},
], "responses": {"200": "Updated cart", "400": "Out of stock", "404": "Product not found"}},
{"method": "GET", "path": "/api/v2/cart", "desc": "Get current cart contents", "params": [], "responses": {"200": "Cart with items, totals, and applicable discounts"}},
{"method": "DELETE", "path": "/api/v2/cart/items/{product_id}", "desc": "Remove item from cart", "params": [
{"name": "product_id", "type": "integer", "required": True, "default": None, "desc": "Product ID to remove"},
], "responses": {"200": "Updated cart", "404": "Item not in cart"}},
{"method": "POST", "path": "/api/v2/subscriptions", "desc": "Create a recurring subscription", "params": [
{"name": "plan_id", "type": "string", "required": True, "default": None, "desc": "Subscription plan ID"},
{"name": "payment_method", "type": "string", "required": True, "default": None, "desc": "Payment method token"},
{"name": "billing_cycle", "type": "string", "required": False, "default": "monthly", "desc": "Billing cycle: monthly, quarterly, annual"},
], "responses": {"201": "Subscription created", "400": "Invalid plan or payment", "402": "Payment failed"}},
{"method": "GET", "path": "/api/v2/shipping/rates", "desc": "Calculate shipping rates", "params": [
{"name": "country", "type": "string", "required": True, "default": None, "desc": "ISO 3166-1 alpha-2 country code"},
{"name": "weight_kg", "type": "number", "required": True, "default": None, "desc": "Total weight in kg"},
{"name": "postal_code", "type": "string", "required": False, "default": None, "desc": "Destination postal code"},
], "responses": {"200": "Available shipping methods with rates", "400": "Invalid country or weight"}},
{"method": "POST", "path": "/api/v2/webhooks", "desc": "Register a webhook endpoint", "params": [
{"name": "url", "type": "string", "required": True, "default": None, "desc": "HTTPS callback URL"},
{"name": "events", "type": "array", "required": True, "default": None, "desc": "Events to subscribe: order.created, order.shipped, payment.received"},
{"name": "secret", "type": "string", "required": False, "default": None, "desc": "Signing secret for payload verification"},
], "responses": {"201": "Webhook registered", "400": "Invalid URL or events", "409": "URL already registered"}},
{"method": "GET", "path": "/api/v2/analytics/sales", "desc": "Get sales analytics summary", "params": [
{"name": "period", "type": "string", "required": True, "default": None, "desc": "Period: today, week, month, quarter, year"},
{"name": "group_by", "type": "string", "required": False, "default": "day", "desc": "Group by: day, week, month"},
{"name": "category", "type": "string", "required": False, "default": None, "desc": "Filter by category slug"},
], "responses": {"200": "Sales data with revenue, orders count, average order value", "400": "Invalid period", "403": "Admin access required"}},
{"method": "POST", "path": "/api/v2/coupons", "desc": "Create a coupon code", "params": [
{"name": "code", "type": "string", "required": True, "default": None, "desc": "Unique coupon code"},
{"name": "discount_type", "type": "string", "required": True, "default": None, "desc": "Type: percentage, fixed_amount, free_shipping"},
{"name": "discount_value", "type": "number", "required": True, "default": None, "desc": "Discount value (% or EUR amount)"},
{"name": "min_order", "type": "number", "required": False, "default": 0, "desc": "Minimum order amount"},
{"name": "max_uses", "type": "integer", "required": False, "default": None, "desc": "Maximum total uses (null = unlimited)"},
{"name": "expires_at", "type": "string", "required": False, "default": None, "desc": "Expiration date (ISO 8601)"},
], "responses": {"201": "Coupon created", "400": "Validation error", "409": "Coupon code already exists"}},
{"method": "GET", "path": "/api/v2/inventory", "desc": "Get inventory levels", "params": [
{"name": "product_ids", "type": "array", "required": False, "default": None, "desc": "Filter by product IDs (comma-separated)"},
{"name": "low_stock", "type": "boolean", "required": False, "default": False, "desc": "Only show items with stock < threshold"},
{"name": "threshold", "type": "integer", "required": False, "default": 10, "desc": "Low stock threshold"},
], "responses": {"200": "Inventory levels per product with warehouse breakdown", "403": "Admin access required"}},
{"method": "POST", "path": "/api/v2/exports", "desc": "Request data export", "params": [
{"name": "type", "type": "string", "required": True, "default": None, "desc": "Export type: orders, customers, products, reviews"},
{"name": "format", "type": "string", "required": False, "default": "csv", "desc": "Format: csv, json, xlsx"},
{"name": "date_from", "type": "string", "required": False, "default": None, "desc": "Start date filter (ISO 8601)"},
{"name": "date_to", "type": "string", "required": False, "default": None, "desc": "End date filter (ISO 8601)"},
], "responses": {"202": "Export queued, download URL sent via email", "400": "Invalid parameters", "403": "Admin access required"}},
{"method": "GET", "path": "/api/v2/search", "desc": "Full-text product search with filters", "params": [
{"name": "q", "type": "string", "required": True, "default": None, "desc": "Search query"},
{"name": "category", "type": "string", "required": False, "default": None, "desc": "Category filter"},
{"name": "price_min", "type": "number", "required": False, "default": None, "desc": "Minimum price"},
{"name": "price_max", "type": "number", "required": False, "default": None, "desc": "Maximum price"},
{"name": "in_stock", "type": "boolean", "required": False, "default": None, "desc": "Only in-stock items"},
{"name": "sort", "type": "string", "required": False, "default": "relevance", "desc": "Sort: relevance, price_asc, price_desc, rating"},
], "responses": {"200": "Search results with facets and total count", "400": "Query too short (min 2 chars)"}},
{"method": "PUT", "path": "/api/v2/products/{id}/inventory", "desc": "Update product inventory", "params": [
{"name": "id", "type": "integer", "required": True, "default": None, "desc": "Product ID"},
{"name": "quantity", "type": "integer", "required": True, "default": None, "desc": "New stock quantity"},
{"name": "warehouse", "type": "string", "required": False, "default": "default", "desc": "Warehouse identifier"},
{"name": "reason", "type": "string", "required": False, "default": None, "desc": "Reason for adjustment"},
], "responses": {"200": "Updated inventory", "400": "Invalid quantity", "404": "Product not found"}},
{"method": "POST", "path": "/api/v2/notifications/send", "desc": "Send notification to customer", "params": [
{"name": "customer_id", "type": "integer", "required": True, "default": None, "desc": "Target customer ID"},