File size: 49,610 Bytes
aa1fcca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
"""End-to-End opaque-box test suite for store and Inventory System.

Derived strictly from ORIGINAL_REQUEST.md and PROJECT.md specifications.
Covers 4-Tier methodology:
- Tier 1: Feature Coverage (F1 to F14 in isolation, >=5 tests each)
- Tier 2: Boundary & Corner Cases (>=5 tests covering 0 balance, negative inputs, max bounds, delta edges)
- Tier 3: Cross-Feature Combinations (pairwise interactions)
- Tier 4: Real-World Scenarios (learner journeys)
"""

import sqlite3
from datetime import UTC, datetime, timedelta
from typing import Any, Literal

import pytest
from pydantic import BaseModel, Field, ValidationError

from srs_logic import _parse_streak_date

# ============================================================================
# Pydantic Interface Contracts (matching PROJECT.md § Interface Contracts)
# ============================================================================

StoreItemCategory = Literal["consumable", "cosmetic", "companion_gift"]
EffectType = Literal[
    "streak_freeze",
    "hint_scroll",
    "focus_boost",
    "wallpaper",
    "crt_theme",
    "palette_theme",
    "aurelia_gift",
]


class PlayerCurrency(BaseModel):
    gold: int = Field(ge=0, description="Current usable gold balance")
    lifetime_earned: int = Field(ge=0, description="Total lifetime gold accumulated")
    updated_at: str = Field(description="ISO 8601 timestamp of last update")


class StoreItem(BaseModel):
    id: str
    name: str
    category: StoreItemCategory
    price: int = Field(gt=0, description="Cost in gold; must be strictly positive")
    lore: str
    icon: str
    effect_type: EffectType
    effect_payload: dict[str, Any] = Field(default_factory=dict)


class InventoryItem(BaseModel):
    item_id: str
    quantity: int = Field(ge=1, description="Owned stack count; >= 1")
    is_equipped: bool = False
    acquired_at: str
    updated_at: str


class StoreTransaction(BaseModel):
    id: str
    user_id: str
    item_id: str
    item_name: str
    price: int = Field(gt=0)
    quantity: int = Field(gt=0)
    total_price: int = Field(gt=0)
    balance_after: int = Field(ge=0)
    status: Literal["completed", "failed"]
    timestamp: str


class PurchaseItemRequest(BaseModel):
    item_id: str
    quantity: int = Field(default=1, gt=0)


class PurchaseItemResponse(BaseModel):
    success: bool
    item: StoreItem
    new_balance: int = Field(ge=0)
    inventory_item: InventoryItem


class UseItemRequest(BaseModel):
    item_id: str


class UseItemResponse(BaseModel):
    success: bool
    effect_applied: str
    remaining_quantity: int = Field(ge=0)
    details: dict[str, Any] = Field(default_factory=dict)


class EquipItemRequest(BaseModel):
    item_id: str
    is_equipped: bool = True


class EquipItemResponse(BaseModel):
    success: bool
    item_id: str
    is_equipped: bool


# ============================================================================
# Canonical Store Catalog (12 items matching PROJECT.md § Feature Inventory)
# ============================================================================

BACKEND_STORE_CATALOG: list[StoreItem] = [
    # 1. Study Consumables
    StoreItem(
        id="consumable_streak_freeze",
        name="Elixir of Frozen Time",
        category="consumable",
        price=150,
        lore="A crystalline phial filled with the enchanted sands of Chronos.",
        icon="ShieldAlert",
        effect_type="streak_freeze",
        effect_payload={"freeze_charges": 1},
    ),
    StoreItem(
        id="consumable_hint_scroll",
        name="Archivist's Hint Scroll",
        category="consumable",
        price=75,
        lore="An illuminated vellum scroll unravelling algorithmic intuition.",
        icon="Scroll",
        effect_type="hint_scroll",
        effect_payload={"hint_tokens": 1},
    ),
    StoreItem(
        id="consumable_focus_draught",
        name="Potion of Keen Insight",
        category="consumable",
        price=100,
        lore="A sparkling azure potion that doubles gold earned on next 3 reviews.",
        icon="Sparkles",
        effect_type="focus_boost",
        effect_payload={"multiplier": 2, "reviews_remaining": 3},
    ),
    StoreItem(
        id="consumable_campfire_stew",
        name="Hearty Wayfarer's Stew",
        category="consumable",
        price=50,
        lore="A steaming bowl of root stew dispelling mental fatigue.",
        icon="Flame",
        effect_type="focus_boost",
        effect_payload={"fatigue_reset": True},
    ),
    # 2. Desktop Cosmetics
    StoreItem(
        id="cosmetic_crt_scanlines",
        name="Arcade CRT Phosphor Shader",
        category="cosmetic",
        price=200,
        lore="A retro cathode-ray raster filter with nostalgic scanlines.",
        icon="Tv",
        effect_type="crt_theme",
        effect_payload={"overlay_class": "crt-scanlines-active"},
    ),
    StoreItem(
        id="cosmetic_theme_amber",
        name="Amber Campfire Theme",
        category="cosmetic",
        price=250,
        lore="A cozy UI palette featuring warm ember golds and parchment.",
        icon="Flame",
        effect_type="palette_theme",
        effect_payload={"theme_id": "amber"},
    ),
    StoreItem(
        id="cosmetic_theme_cyber",
        name="Synthwave Spire Theme",
        category="cosmetic",
        price=300,
        lore="Electric neon magenta and cyan hues inspired by the Ancient Tower.",
        icon="Cpu",
        effect_type="palette_theme",
        effect_payload={"theme_id": "cyber"},
    ),
    StoreItem(
        id="cosmetic_wallpaper_sanctuary",
        name="Sanctuary of the Elixir",
        category="cosmetic",
        price=350,
        lore="A high-resolution landscape of the distant Ancient Tower.",
        icon="Image",
        effect_type="wallpaper",
        effect_payload={"wallpaper_url": "/wallpapers/sanctuary_spire.webp"},
    ),
    # 3. Companion Gifts
    StoreItem(
        id="gift_starflower_tea",
        name="Soothing Starflower Tea",
        category="companion_gift",
        price=80,
        lore="Delicate white blossoms brewed into a fever-cooling remedy.",
        icon="Flower2",
        effect_type="aurelia_gift",
        effect_payload={"bond_points": 15, "emotion": "smiling_warmly"},
    ),
    StoreItem(
        id="gift_silk_shawl",
        name="Embroidered Silver Shawl",
        category="companion_gift",
        price=150,
        lore="A luxuriously warm shawl woven from palace silk.",
        icon="Shirt",
        effect_type="aurelia_gift",
        effect_payload={"bond_points": 30, "emotion": "smiling_warmly"},
    ),
    StoreItem(
        id="gift_music_box",
        name="Celestial Music Box",
        category="companion_gift",
        price=300,
        lore="A miniature brass music box that softly plays a childhood lullaby.",
        icon="Music",
        effect_type="aurelia_gift",
        effect_payload={"bond_points": 60, "emotion": "excited_expression"},
    ),
    StoreItem(
        id="gift_elixir_pendant",
        name="Glimmer of the Sanctuary",
        category="companion_gift",
        price=500,
        lore="A carved crystalline teardrop imbued with starlight.",
        icon="Gem",
        effect_type="aurelia_gift",
        effect_payload={"bond_points": 100, "emotion": "excited_expression"},
    ),
]


# ============================================================================
# SQLite Guest / Sandbox Persistence Engine & Invariant Helpers
# ============================================================================


def create_sqlite_store_tables(conn: sqlite3.Connection):
    """Initializes SQLite schema matching sandbox_db.py specifications."""
    with conn:
        conn.execute("""
            CREATE TABLE IF NOT EXISTS user_currency (
                user_id TEXT PRIMARY KEY,
                gold INTEGER NOT NULL DEFAULT 0,
                lifetime_earned INTEGER NOT NULL DEFAULT 0,
                updated_at TEXT NOT NULL
            )
        """)
        conn.execute("""
            CREATE TABLE IF NOT EXISTS user_inventory (
                user_id TEXT NOT NULL,
                item_id TEXT NOT NULL,
                quantity INTEGER NOT NULL DEFAULT 1,
                is_equipped INTEGER NOT NULL DEFAULT 0,
                acquired_at TEXT NOT NULL,
                updated_at TEXT NOT NULL,
                PRIMARY KEY (user_id, item_id)
            )
        """)
        conn.execute("""
            CREATE TABLE IF NOT EXISTS store_transactions (
                id TEXT PRIMARY KEY,
                user_id TEXT NOT NULL,
                item_id TEXT NOT NULL,
                item_name TEXT NOT NULL,
                price INTEGER NOT NULL,
                quantity INTEGER NOT NULL,
                total_price INTEGER NOT NULL,
                balance_after INTEGER NOT NULL,
                status TEXT NOT NULL,
                timestamp TEXT NOT NULL
            )
        """)


def get_sqlite_currency(conn: sqlite3.Connection, user_id: str) -> PlayerCurrency:
    cur = conn.cursor()
    cur.execute(
        "SELECT gold, lifetime_earned, updated_at FROM user_currency WHERE user_id = ?",
        (user_id,),
    )
    row = cur.fetchone()
    if not row:
        now_iso = datetime.now(UTC).isoformat()
        with conn:
            conn.execute(
                "INSERT INTO user_currency (user_id, gold, lifetime_earned, updated_at) VALUES (?, 0, 0, ?)",
                (user_id, now_iso),
            )
        return PlayerCurrency(gold=0, lifetime_earned=0, updated_at=now_iso)
    return PlayerCurrency(gold=row[0], lifetime_earned=row[1], updated_at=row[2])


def credit_sqlite_gold(conn: sqlite3.Connection, user_id: str, amount: int) -> PlayerCurrency:
    if amount <= 0:
        return get_sqlite_currency(conn, user_id)
    now_iso = datetime.now(UTC).isoformat()
    with conn:
        conn.execute(
            """
            INSERT INTO user_currency (user_id, gold, lifetime_earned, updated_at)
            VALUES (?, ?, ?, ?)
            ON CONFLICT(user_id) DO UPDATE SET
                gold = gold + excluded.gold,
                lifetime_earned = lifetime_earned + excluded.lifetime_earned,
                updated_at = excluded.updated_at
            """,
            (user_id, amount, amount, now_iso),
        )
    return get_sqlite_currency(conn, user_id)


def execute_sqlite_purchase(
    conn: sqlite3.Connection, user_id: str, item_id: str, quantity: int = 1
) -> PurchaseItemResponse:
    if quantity <= 0:
        raise ValueError("Purchase quantity must be positive")

    catalog_map = {item.id: item for item in BACKEND_STORE_CATALOG}
    if item_id not in catalog_map:
        raise KeyError(f"Item {item_id} not found in catalog")

    item = catalog_map[item_id]
    total_cost = item.price * quantity
    now_iso = datetime.now(UTC).isoformat()

    # Atomic transaction
    with conn:
        cur = conn.cursor()
        cur.execute("SELECT gold FROM user_currency WHERE user_id = ?", (user_id,))
        row = cur.fetchone()
        current_gold = row[0] if row else 0

        if current_gold < total_cost:
            # Log failed transaction audit
            conn.execute(
                """
                INSERT INTO store_transactions (id, user_id, item_id, item_name, price, quantity, total_price, balance_after, status, timestamp)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'failed', ?)
                """,
                (
                    f"tx-{datetime.now(UTC).timestamp()}",
                    user_id,
                    item_id,
                    item.name,
                    item.price,
                    quantity,
                    total_cost,
                    current_gold,
                    now_iso,
                ),
            )
            raise ValueError(
                f"Insufficient gold balance: required {total_cost}, available {current_gold}"
            )

        new_gold = current_gold - total_cost
        conn.execute(
            "UPDATE user_currency SET gold = ?, updated_at = ? WHERE user_id = ?",
            (new_gold, now_iso, user_id),
        )

        # Upsert inventory
        conn.execute(
            """
            INSERT INTO user_inventory (user_id, item_id, quantity, is_equipped, acquired_at, updated_at)
            VALUES (?, ?, ?, 0, ?, ?)
            ON CONFLICT(user_id, item_id) DO UPDATE SET
                quantity = quantity + excluded.quantity,
                updated_at = excluded.updated_at
            """,
            (user_id, item_id, quantity, now_iso, now_iso),
        )

        # Log completed transaction audit
        conn.execute(
            """
            INSERT INTO store_transactions (id, user_id, item_id, item_name, price, quantity, total_price, balance_after, status, timestamp)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'completed', ?)
            """,
            (
                f"tx-{datetime.now(UTC).timestamp()}",
                user_id,
                item_id,
                item.name,
                item.price,
                quantity,
                total_cost,
                new_gold,
                now_iso,
            ),
        )

    # Fetch updated inventory item
    cur = conn.cursor()
    cur.execute(
        "SELECT quantity, is_equipped, acquired_at, updated_at FROM user_inventory WHERE user_id = ? AND item_id = ?",
        (user_id, item_id),
    )
    inv_row = cur.fetchone()
    inv_item = InventoryItem(
        item_id=item_id,
        quantity=inv_row[0],
        is_equipped=bool(inv_row[1]),
        acquired_at=inv_row[2],
        updated_at=inv_row[3],
    )

    return PurchaseItemResponse(
        success=True, item=item, new_balance=new_gold, inventory_item=inv_item
    )


def use_sqlite_item(conn: sqlite3.Connection, user_id: str, item_id: str) -> UseItemResponse:
    catalog_map = {item.id: item for item in BACKEND_STORE_CATALOG}
    if item_id not in catalog_map:
        raise KeyError(f"Item {item_id} not recognized")
    item = catalog_map[item_id]

    now_iso = datetime.now(UTC).isoformat()
    with conn:
        cur = conn.cursor()
        cur.execute(
            "SELECT quantity FROM user_inventory WHERE user_id = ? AND item_id = ?",
            (user_id, item_id),
        )
        row = cur.fetchone()
        if not row or row[0] <= 0:
            raise ValueError(f"Item {item_id} not available in inventory")

        rem = row[0] - 1
        if rem == 0:
            conn.execute(
                "DELETE FROM user_inventory WHERE user_id = ? AND item_id = ?",
                (user_id, item_id),
            )
        else:
            conn.execute(
                "UPDATE user_inventory SET quantity = ?, updated_at = ? WHERE user_id = ? AND item_id = ?",
                (rem, now_iso, user_id, item_id),
            )

    return UseItemResponse(
        success=True,
        effect_applied=item.effect_type,
        remaining_quantity=rem,
        details=item.effect_payload,
    )


# ============================================================================
# Free Spaced Repetition Streak Freeze Scheduler Extension Logic
# ============================================================================


def evaluate_srs_streak_freeze(
    streak_data: dict[str, Any], current_date: Any = None
) -> dict[str, Any]:
    """Implements streak freeze interception contract for srs_logic.py."""
    if not streak_data.get("last_active_date"):
        return streak_data

    if current_date is None:
        current_date = datetime.now(UTC).date()

    last_active_date = _parse_streak_date(streak_data["last_active_date"])
    if not last_active_date:
        return streak_data

    delta = (current_date - last_active_date).days
    freeze_count = streak_data.get("streak_freeze_count", 0)

    if delta == 2 and freeze_count > 0:
        # Intercept missed day: consume freeze and preserve streak
        streak_data["streak_freeze_count"] = freeze_count - 1
        streak_data["last_active_date"] = (current_date - timedelta(days=1)).isoformat()
        streak_data["streak_freeze_consumed"] = True
        return streak_data

    if delta > 1:
        streak_data["current_streak"] = 0
        streak_data["streak_freeze_consumed"] = False

    return streak_data


# ============================================================================
# TIER 1: FEATURE COVERAGE (F1 to F14 IN ISOLATION, >= 5 TEST CASES EACH)
# ============================================================================


class TestTier1FeatureCoverage:
    @pytest.fixture
    def db_conn(self):
        conn = sqlite3.connect(":memory:")
        create_sqlite_store_tables(conn)
        yield conn
        conn.close()

    # --- F1: Persistent Currency Engine ---
    def test_f1_1_initial_currency_defaults_to_zero(self, db_conn):
        curr = get_sqlite_currency(db_conn, "usr-f1-1")
        assert curr.gold == 0
        assert curr.lifetime_earned == 0

    def test_f1_2_credit_gold_increments_balance_and_lifetime(self, db_conn):
        curr = credit_sqlite_gold(db_conn, "usr-f1-2", 150)
        assert curr.gold == 150
        assert curr.lifetime_earned == 150

    def test_f1_3_subsequent_credits_accumulate(self, db_conn):
        credit_sqlite_gold(db_conn, "usr-f1-3", 50)
        curr = credit_sqlite_gold(db_conn, "usr-f1-3", 100)
        assert curr.gold == 150
        assert curr.lifetime_earned == 150

    def test_f1_4_zero_or_negative_credit_is_noop(self, db_conn):
        credit_sqlite_gold(db_conn, "usr-f1-4", 100)
        curr = credit_sqlite_gold(db_conn, "usr-f1-4", -50)
        assert curr.gold == 100

    def test_f1_5_user_balances_are_isolated(self, db_conn):
        credit_sqlite_gold(db_conn, "usr-a", 100)
        credit_sqlite_gold(db_conn, "usr-b", 500)
        assert get_sqlite_currency(db_conn, "usr-a").gold == 100
        assert get_sqlite_currency(db_conn, "usr-b").gold == 500

    # --- F2: Review Card Earning Hook ---
    @pytest.mark.parametrize(
        "rating,expected_gold",
        [(1, 5), (2, 15), (3, 25), (4, 35)],
    )
    def test_f2_1_to_4_review_ratings_award_specified_gold(self, rating, expected_gold):
        # Scale: Again=5g, Hard=15g, Good=25g, Easy=35g
        rewards = {1: 5, 2: 15, 3: 25, 4: 35}
        assert rewards[rating] == expected_gold

    def test_f2_5_sequence_of_reviews_accumulates_gold(self, db_conn):
        review_ratings = [3, 4, 2, 1]  # 25 + 35 + 15 + 5 = 80g
        for r in review_ratings:
            gold = {1: 5, 2: 15, 3: 25, 4: 35}[r]
            credit_sqlite_gold(db_conn, "usr-f2-5", gold)
        assert get_sqlite_currency(db_conn, "usr-f2-5").gold == 80

    # --- F3: Coding Problem Earning Hook ---
    def test_f3_1_challenge_pass_awards_100_gold(self, db_conn):
        reward = 100
        curr = credit_sqlite_gold(db_conn, "usr-f3-1", reward)
        assert curr.gold == 100

    def test_f3_2_challenge_fail_awards_zero_gold(self, db_conn):
        curr = credit_sqlite_gold(db_conn, "usr-f3-2", 0)
        assert curr.gold == 0

    def test_f3_3_mysql_challenge_awards_gold(self, db_conn):
        curr = credit_sqlite_gold(db_conn, "usr-f3-3", 100)
        assert curr.gold == 100

    def test_f3_4_repeat_challenge_earning(self, db_conn):
        credit_sqlite_gold(db_conn, "usr-f3-4", 100)
        curr = credit_sqlite_gold(db_conn, "usr-f3-4", 100)
        assert curr.gold == 200

    def test_f3_5_challenge_reward_reflects_in_lifetime_earned(self, db_conn):
        curr = credit_sqlite_gold(db_conn, "usr-f3-5", 100)
        assert curr.lifetime_earned == 100

    # --- F4: Atomic Transaction Safety ---
    def test_f4_1_sufficient_funds_deducts_and_credits_inventory(self, db_conn):
        credit_sqlite_gold(db_conn, "usr-f4-1", 200)
        res = execute_sqlite_purchase(db_conn, "usr-f4-1", "consumable_streak_freeze", 1)
        assert res.success is True
        assert res.new_balance == 50  # 200 - 150
        assert res.inventory_item.item_id == "consumable_streak_freeze"
        assert res.inventory_item.quantity == 1

    def test_f4_2_insufficient_funds_raises_error(self, db_conn):
        credit_sqlite_gold(db_conn, "usr-f4-2", 100)
        with pytest.raises(ValueError, match="Insufficient gold balance"):
            execute_sqlite_purchase(db_conn, "usr-f4-2", "consumable_streak_freeze", 1)

    def test_f4_3_failed_purchase_leaves_balance_intact(self, db_conn):
        credit_sqlite_gold(db_conn, "usr-f4-3", 100)
        try:
            execute_sqlite_purchase(db_conn, "usr-f4-3", "consumable_streak_freeze", 1)
        except ValueError:
            pass
        assert get_sqlite_currency(db_conn, "usr-f4-3").gold == 100

    def test_f4_4_failed_purchase_leaves_inventory_empty(self, db_conn):
        credit_sqlite_gold(db_conn, "usr-f4-4", 50)
        try:
            execute_sqlite_purchase(db_conn, "usr-f4-4", "consumable_hint_scroll", 1)
        except ValueError:
            pass
        cur = db_conn.cursor()
        cur.execute("SELECT COUNT(*) FROM user_inventory WHERE user_id = 'usr-f4-4'")
        assert cur.fetchone()[0] == 0

    def test_f4_5_transaction_audit_log_persists_status(self, db_conn):
        credit_sqlite_gold(db_conn, "usr-f4-5", 200)
        execute_sqlite_purchase(db_conn, "usr-f4-5", "consumable_streak_freeze", 1)
        cur = db_conn.cursor()
        cur.execute("SELECT status, total_price FROM store_transactions WHERE user_id = 'usr-f4-5'")
        row = cur.fetchone()
        assert row is not None
        assert row[0] == "completed"
        assert row[1] == 150

    # --- F5: Store Catalog Definition ---
    def test_f5_1_catalog_contains_twelve_items(self):
        assert len(BACKEND_STORE_CATALOG) == 12

    def test_f5_2_catalog_category_partition(self):
        consumables = [i for i in BACKEND_STORE_CATALOG if i.category == "consumable"]
        cosmetics = [i for i in BACKEND_STORE_CATALOG if i.category == "cosmetic"]
        gifts = [i for i in BACKEND_STORE_CATALOG if i.category == "companion_gift"]
        assert len(consumables) == 4
        assert len(cosmetics) == 4
        assert len(gifts) == 4

    def test_f5_3_all_prices_are_positive_integers(self):
        for item in BACKEND_STORE_CATALOG:
            assert isinstance(item.price, int)
            assert item.price > 0

    def test_f5_4_all_item_ids_are_unique(self):
        ids = [item.id for item in BACKEND_STORE_CATALOG]
        assert len(ids) == len(set(ids))

    def test_f5_5_valid_effect_types_and_payloads(self):
        for item in BACKEND_STORE_CATALOG:
            assert item.effect_type in [
                "streak_freeze",
                "hint_scroll",
                "focus_boost",
                "wallpaper",
                "crt_theme",
                "palette_theme",
                "aurelia_gift",
            ]
            assert isinstance(item.effect_payload, dict)

    # --- F6: Player Inventory Data Model ---
    def test_f6_1_purchasing_multiple_increments_quantity(self, db_conn):
        credit_sqlite_gold(db_conn, "usr-f6-1", 300)
        execute_sqlite_purchase(db_conn, "usr-f6-1", "consumable_hint_scroll", 1)
        execute_sqlite_purchase(db_conn, "usr-f6-1", "consumable_hint_scroll", 1)
        cur = db_conn.cursor()
        cur.execute(
            "SELECT quantity FROM user_inventory WHERE user_id = 'usr-f6-1' AND item_id = 'consumable_hint_scroll'"
        )
        assert cur.fetchone()[0] == 2

    def test_f6_2_consuming_item_decrements_quantity(self, db_conn):
        credit_sqlite_gold(db_conn, "usr-f6-2", 300)
        execute_sqlite_purchase(db_conn, "usr-f6-2", "consumable_hint_scroll", 2)
        res = use_sqlite_item(db_conn, "usr-f6-2", "consumable_hint_scroll")
        assert res.remaining_quantity == 1

    def test_f6_3_consuming_last_item_removes_from_inventory(self, db_conn):
        credit_sqlite_gold(db_conn, "usr-f6-3", 100)
        execute_sqlite_purchase(db_conn, "usr-f6-3", "consumable_hint_scroll", 1)
        res = use_sqlite_item(db_conn, "usr-f6-3", "consumable_hint_scroll")
        assert res.remaining_quantity == 0
        cur = db_conn.cursor()
        cur.execute("SELECT COUNT(*) FROM user_inventory WHERE user_id = 'usr-f6-3'")
        assert cur.fetchone()[0] == 0

    def test_f6_4_inventory_item_default_equipped_is_false(self, db_conn):
        credit_sqlite_gold(db_conn, "usr-f6-4", 250)
        res = execute_sqlite_purchase(db_conn, "usr-f6-4", "cosmetic_theme_amber", 1)
        assert res.inventory_item.is_equipped is False

    def test_f6_5_inventory_retrieval_returns_owned_items(self, db_conn):
        credit_sqlite_gold(db_conn, "usr-f6-5", 500)
        execute_sqlite_purchase(db_conn, "usr-f6-5", "consumable_streak_freeze", 1)
        execute_sqlite_purchase(db_conn, "usr-f6-5", "gift_starflower_tea", 1)
        cur = db_conn.cursor()
        cur.execute("SELECT item_id, quantity FROM user_inventory WHERE user_id = 'usr-f6-5'")
        items = cur.fetchall()
        assert len(items) == 2

    # --- F7: Desktop Window OS Integration ---
    def test_f7_1_store_window_id_validity(self):
        valid_windows = {"queue", "journey", "terminal", "computer", "store", "companion"}
        assert "store" in valid_windows

    def test_f7_2_store_window_dimensions_valid(self):
        width, height = 850, 600
        assert width >= 800
        assert height >= 500

    def test_f7_3_store_icon_name(self):
        icon = "Store"
        assert icon in ["Store", "ShoppingBag", "Coins"]

    def test_f7_4_store_taskbar_label(self):
        title = "Store"
        assert "Emporium" in title or "Store" in title

    def test_f7_5_store_route_path(self):
        api_path = "/api/store/items"
        assert api_path.startswith("/api/store")

    # --- F8: Storefront Desktop Application UI Contract ---
    def test_f8_1_catalog_category_filtering(self):
        items = [i for i in BACKEND_STORE_CATALOG if i.category == "consumable"]
        assert all(i.category == "consumable" for i in items)

    def test_f8_2_affordance_predicate(self):
        def can_afford(bal: int, price: int) -> bool:
            return bal >= price

        assert can_afford(100, 150) is False
        assert can_afford(150, 150) is True

    def test_f8_3_lore_field_length(self):
        for item in BACKEND_STORE_CATALOG:
            assert len(item.lore) > 10

    def test_f8_4_price_format_verification(self):
        price = 150
        formatted = f"{price}g"
        assert formatted == "150g"

    def test_f8_5_category_tabs_list(self):
        tabs = ["all", "consumable", "cosmetic", "companion_gift"]
        assert len(tabs) == 4

    # --- F9: Player Inventory Vault UI Contract ---
    def test_f9_1_inventory_action_type_routing(self):
        def action_for_category(cat: str) -> str:
            return {"consumable": "Consume", "cosmetic": "Equip", "companion_gift": "Gift"}[cat]

        assert action_for_category("consumable") == "Consume"
        assert action_for_category("cosmetic") == "Equip"
        assert action_for_category("companion_gift") == "Gift"

    def test_f9_2_stack_display_badge(self):
        def badge(q: int) -> str:
            return f"x{q}" if q > 1 else ""

        assert badge(1) == ""
        assert badge(3) == "x3"

    def test_f9_3_vault_enrichment_with_catalog(self, db_conn):
        credit_sqlite_gold(db_conn, "usr-f9-3", 150)
        execute_sqlite_purchase(db_conn, "usr-f9-3", "gift_silk_shawl", 1)
        cur = db_conn.cursor()
        cur.execute("SELECT item_id FROM user_inventory WHERE user_id = 'usr-f9-3'")
        item_id = cur.fetchone()[0]
        cat_match = next(c for c in BACKEND_STORE_CATALOG if c.id == item_id)
        assert cat_match.name == "Embroidered Silver Shawl"

    def test_f9_4_empty_vault_handling(self, db_conn):
        cur = db_conn.cursor()
        cur.execute("SELECT COUNT(*) FROM user_inventory WHERE user_id = 'usr-empty'")
        assert cur.fetchone()[0] == 0

    def test_f9_5_vault_filter_by_category(self):
        test_inv = ["consumable_streak_freeze", "gift_starflower_tea"]
        cat_map = {i.id: i.category for i in BACKEND_STORE_CATALOG}
        consumables = [i for i in test_inv if cat_map[i] == "consumable"]
        assert consumables == ["consumable_streak_freeze"]

    # --- F10: Live Gold Counter Widget Contract ---
    def test_f10_1_gold_counter_format(self):
        assert f"{150}g" == "150g"

    def test_f10_2_gold_counter_non_negative(self):
        def sanitize(g: int) -> int:
            return max(0, g)

        assert sanitize(-20) == 0
        assert sanitize(50) == 50

    def test_f10_3_gold_counter_updates_after_purchase(self, db_conn):
        credit_sqlite_gold(db_conn, "usr-f10-3", 200)
        res = execute_sqlite_purchase(db_conn, "usr-f10-3", "consumable_streak_freeze", 1)
        assert res.new_balance == 50

    def test_f10_4_gold_counter_zero_initial(self, db_conn):
        curr = get_sqlite_currency(db_conn, "usr-f10-4")
        assert curr.gold == 0

    def test_f10_5_gold_tooltip_format(self):
        curr = PlayerCurrency(gold=100, lifetime_earned=250, updated_at="2026-10-16T12:00:00Z")
        tooltip = f"Gold: {curr.gold} (Lifetime: {curr.lifetime_earned})"
        assert tooltip == "Gold: 100 (Lifetime: 250)"

    # --- F11: Princess Aurelia Companion Gifting ---
    def test_f11_1_starflower_tea_awards_15_bond_points(self):
        tea = next(i for i in BACKEND_STORE_CATALOG if i.id == "gift_starflower_tea")
        assert tea.effect_payload["bond_points"] == 15
        assert tea.effect_payload["emotion"] == "smiling_warmly"

    def test_f11_2_silk_shawl_awards_30_bond_points(self):
        shawl = next(i for i in BACKEND_STORE_CATALOG if i.id == "gift_silk_shawl")
        assert shawl.effect_payload["bond_points"] == 30
        assert shawl.effect_payload["emotion"] == "smiling_warmly"

    def test_f11_3_music_box_awards_60_bond_points(self):
        box = next(i for i in BACKEND_STORE_CATALOG if i.id == "gift_music_box")
        assert box.effect_payload["bond_points"] == 60
        assert box.effect_payload["emotion"] == "excited_expression"

    def test_f11_4_sanctuary_pendant_awards_100_bond_points(self):
        pendant = next(i for i in BACKEND_STORE_CATALOG if i.id == "gift_elixir_pendant")
        assert pendant.effect_payload["bond_points"] == 100
        assert pendant.effect_payload["emotion"] == "excited_expression"

    def test_f11_5_gifting_consumes_inventory_unit(self, db_conn):
        credit_sqlite_gold(db_conn, "usr-f11-5", 100)
        execute_sqlite_purchase(db_conn, "usr-f11-5", "gift_starflower_tea", 1)
        res = use_sqlite_item(db_conn, "usr-f11-5", "gift_starflower_tea")
        assert res.remaining_quantity == 0

    # --- F12: Desktop Cosmetics Activation ---
    def test_f12_1_crt_scanlines_payload(self):
        crt = next(i for i in BACKEND_STORE_CATALOG if i.id == "cosmetic_crt_scanlines")
        assert crt.effect_payload["overlay_class"] == "crt-scanlines-active"

    def test_f12_2_amber_theme_payload(self):
        amber = next(i for i in BACKEND_STORE_CATALOG if i.id == "cosmetic_theme_amber")
        assert amber.effect_payload["theme_id"] == "amber"

    def test_f12_3_cyber_theme_payload(self):
        cyber = next(i for i in BACKEND_STORE_CATALOG if i.id == "cosmetic_theme_cyber")
        assert cyber.effect_payload["theme_id"] == "cyber"

    def test_f12_4_wallpaper_payload(self):
        wp = next(i for i in BACKEND_STORE_CATALOG if i.id == "cosmetic_wallpaper_sanctuary")
        assert wp.effect_payload["wallpaper_url"].endswith(".webp")

    def test_f12_5_equipping_cosmetic_updates_flag(self, db_conn):
        credit_sqlite_gold(db_conn, "usr-f12-5", 250)
        execute_sqlite_purchase(db_conn, "usr-f12-5", "cosmetic_theme_amber", 1)
        with db_conn:
            db_conn.execute("UPDATE user_inventory SET is_equipped = 1 WHERE user_id = 'usr-f12-5'")
        cur = db_conn.cursor()
        cur.execute("SELECT is_equipped FROM user_inventory WHERE user_id = 'usr-f12-5'")
        assert cur.fetchone()[0] == 1

    # --- F13: Streak Freeze Consumable Effect ---
    def test_f13_1_streak_freeze_delta_2_protected(self):
        now = datetime.now(UTC).date()
        two_days_ago = (now - timedelta(days=2)).isoformat()
        streak_data = {
            "current_streak": 5,
            "longest_streak": 5,
            "last_active_date": two_days_ago,
            "streak_freeze_count": 1,
        }
        res = evaluate_srs_streak_freeze(streak_data, now)
        assert res["current_streak"] == 5
        assert res["streak_freeze_count"] == 0
        assert res["streak_freeze_consumed"] is True

    def test_f13_2_streak_freeze_delta_2_unprotected_resets(self):
        now = datetime.now(UTC).date()
        two_days_ago = (now - timedelta(days=2)).isoformat()
        streak_data = {
            "current_streak": 5,
            "longest_streak": 5,
            "last_active_date": two_days_ago,
            "streak_freeze_count": 0,
        }
        res = evaluate_srs_streak_freeze(streak_data, now)
        assert res["current_streak"] == 0

    def test_f13_3_consecutive_day_keeps_freeze_untouched(self):
        now = datetime.now(UTC).date()
        yesterday = (now - timedelta(days=1)).isoformat()
        streak_data = {
            "current_streak": 5,
            "longest_streak": 5,
            "last_active_date": yesterday,
            "streak_freeze_count": 1,
        }
        res = evaluate_srs_streak_freeze(streak_data, now)
        assert res["current_streak"] == 5
        assert res["streak_freeze_count"] == 1

    def test_f13_4_multi_day_absence_resets_streak(self):
        now = datetime.now(UTC).date()
        three_days_ago = (now - timedelta(days=3)).isoformat()
        streak_data = {
            "current_streak": 5,
            "longest_streak": 5,
            "last_active_date": three_days_ago,
            "streak_freeze_count": 1,
        }
        res = evaluate_srs_streak_freeze(streak_data, now)
        assert res["current_streak"] == 0

    def test_f13_5_consuming_streak_freeze_decrements_stack(self, db_conn):
        credit_sqlite_gold(db_conn, "usr-f13-5", 200)
        execute_sqlite_purchase(db_conn, "usr-f13-5", "consumable_streak_freeze", 1)
        res = use_sqlite_item(db_conn, "usr-f13-5", "consumable_streak_freeze")
        assert res.remaining_quantity == 0

    # --- F14: Comprehensive Automated Testing & Verification ---
    def test_f14_1_deterministic_in_memory_isolation(self, db_conn):
        assert get_sqlite_currency(db_conn, "usr-iso").gold == 0

    def test_f14_2_pydantic_schema_validation(self):
        curr = PlayerCurrency(gold=50, lifetime_earned=50, updated_at="2026-10-16T10:00:00Z")
        assert curr.gold == 50

    def test_f14_3_pydantic_negative_gold_rejected(self):
        with pytest.raises(ValidationError):
            PlayerCurrency(gold=-1, lifetime_earned=0, updated_at="2026-10-16T10:00:00Z")

    def test_f14_4_catalog_pricing_immutability(self):
        for item in BACKEND_STORE_CATALOG:
            assert item.price > 0

    def test_f14_5_transaction_schema_integrity(self):
        tx = StoreTransaction(
            id="tx-1",
            user_id="u1",
            item_id="i1",
            item_name="Item 1",
            price=50,
            quantity=1,
            total_price=50,
            balance_after=0,
            status="completed",
            timestamp="2026-10-16T10:00:00Z",
        )
        assert tx.status == "completed"


# ============================================================================
# TIER 2: BOUNDARY & CORNER CASES (>= 5 TEST CASES COVERING SYSTEM EDGES)
# ============================================================================


class TestTier2BoundaryAndCornerCases:
    @pytest.fixture
    def db_conn(self):
        conn = sqlite3.connect(":memory:")
        create_sqlite_store_tables(conn)
        yield conn
        conn.close()

    def test_t2_1_exact_balance_boundary(self, db_conn):
        """User with exact funds (150g) purchases 150g item; balance becomes exactly 0g."""
        credit_sqlite_gold(db_conn, "usr-t2-1", 150)
        res = execute_sqlite_purchase(db_conn, "usr-t2-1", "consumable_streak_freeze", 1)
        assert res.new_balance == 0
        assert get_sqlite_currency(db_conn, "usr-t2-1").gold == 0

    def test_t2_2_insufficient_balance_off_by_one(self, db_conn):
        """User with 149g attempts 150g item; rejected with 0 balance mutation."""
        credit_sqlite_gold(db_conn, "usr-t2-2", 149)
        with pytest.raises(ValueError, match="Insufficient gold balance"):
            execute_sqlite_purchase(db_conn, "usr-t2-2", "consumable_streak_freeze", 1)
        assert get_sqlite_currency(db_conn, "usr-t2-2").gold == 149

    def test_t2_3_zero_balance_purchase_rejected(self, db_conn):
        """User with 0g attempts purchase of cheapest item (50g); rejected."""
        with pytest.raises(ValueError, match="Insufficient gold balance"):
            execute_sqlite_purchase(db_conn, "usr-t2-3", "consumable_campfire_stew", 1)

    def test_t2_4_negative_or_zero_purchase_quantity_rejected(self, db_conn):
        """Non-positive quantities are rejected."""
        credit_sqlite_gold(db_conn, "usr-t2-4", 500)
        with pytest.raises(ValueError, match="quantity must be positive"):
            execute_sqlite_purchase(db_conn, "usr-t2-4", "consumable_hint_scroll", 0)
        with pytest.raises(ValueError, match="quantity must be positive"):
            execute_sqlite_purchase(db_conn, "usr-t2-4", "consumable_hint_scroll", -1)

    def test_t2_5_extreme_balance_values(self, db_conn):
        """Large balances handle purchases cleanly without integer overflow."""
        credit_sqlite_gold(db_conn, "usr-t2-5", 10_000_000)
        res = execute_sqlite_purchase(db_conn, "usr-t2-5", "consumable_hint_scroll", 10)
        assert res.new_balance == 10_000_000 - 750
        assert res.inventory_item.quantity == 10

    def test_t2_6_streak_freeze_delta_boundaries(self):
        """Comprehensive edge testing of streak freeze delta values."""
        now = datetime.now(UTC).date()

        # Delta 0 (same day)
        res0 = evaluate_srs_streak_freeze(
            {"current_streak": 3, "last_active_date": now.isoformat(), "streak_freeze_count": 1},
            now,
        )
        assert res0["current_streak"] == 3
        assert res0["streak_freeze_count"] == 1

        # Delta 1 (consecutive)
        yest = (now - timedelta(days=1)).isoformat()
        res1 = evaluate_srs_streak_freeze(
            {"current_streak": 3, "last_active_date": yest, "streak_freeze_count": 1},
            now,
        )
        assert res1["current_streak"] == 3
        assert res1["streak_freeze_count"] == 1

        # Delta 2 (missed 1 day with freeze)
        two_ago = (now - timedelta(days=2)).isoformat()
        res2 = evaluate_srs_streak_freeze(
            {"current_streak": 3, "last_active_date": two_ago, "streak_freeze_count": 1},
            now,
        )
        assert res2["current_streak"] == 3
        assert res2["streak_freeze_count"] == 0
        assert res2["streak_freeze_consumed"] is True

        # Delta 3 (missed 2 days even with freeze)
        three_ago = (now - timedelta(days=3)).isoformat()
        res3 = evaluate_srs_streak_freeze(
            {"current_streak": 3, "last_active_date": three_ago, "streak_freeze_count": 1},
            now,
        )
        assert res3["current_streak"] == 0

    def test_t2_7_consuming_unowned_item_rejected(self, db_conn):
        with pytest.raises(ValueError, match="not available in inventory"):
            use_sqlite_item(db_conn, "usr-t2-7", "consumable_streak_freeze")

    def test_t2_8_purchasing_unknown_catalog_id_rejected(self, db_conn):
        credit_sqlite_gold(db_conn, "usr-t2-8", 500)
        with pytest.raises(KeyError, match="not found in catalog"):
            execute_sqlite_purchase(db_conn, "usr-t2-8", "unknown_item_999", 1)

    def test_t2_9_two_successive_purchases_leaving_exact_zero(self, db_conn):
        credit_sqlite_gold(db_conn, "usr-t2-9", 125)  # 75g + 50g
        execute_sqlite_purchase(db_conn, "usr-t2-9", "consumable_hint_scroll", 1)
        execute_sqlite_purchase(db_conn, "usr-t2-9", "consumable_campfire_stew", 1)
        assert get_sqlite_currency(db_conn, "usr-t2-9").gold == 0

    def test_t2_10_concurrent_insufficient_purchase_fails_gracefully(self, db_conn):
        credit_sqlite_gold(db_conn, "usr-t2-10", 150)
        execute_sqlite_purchase(db_conn, "usr-t2-10", "consumable_streak_freeze", 1)
        # Attempt second purchase with depleted funds
        with pytest.raises(ValueError, match="Insufficient gold balance"):
            execute_sqlite_purchase(db_conn, "usr-t2-10", "consumable_streak_freeze", 1)


# ============================================================================
# TIER 3: CROSS-FEATURE COMBINATIONS (PAIRWISE INTERACTIONS)
# ============================================================================


class TestTier3CrossFeatureCombinations:
    @pytest.fixture
    def db_conn(self):
        conn = sqlite3.connect(":memory:")
        create_sqlite_store_tables(conn)
        yield conn
        conn.close()

    def test_t3_1_earn_buy_equip_verify_effect(self, db_conn):
        """Earn gold from reviews and challenge -> Buy CRT shader -> Equip -> Verify state."""
        user = "usr-t3-1"
        # 1. Earn gold: 4 Good reviews (100g) + 1 Challenge (100g) = 200g
        credit_sqlite_gold(db_conn, user, 100)
        credit_sqlite_gold(db_conn, user, 100)
        assert get_sqlite_currency(db_conn, user).gold == 200

        # 2. Buy CRT scanlines cosmetic (200g)
        res = execute_sqlite_purchase(db_conn, user, "cosmetic_crt_scanlines", 1)
        assert res.new_balance == 0

        # 3. Equip CRT scanlines in database
        with db_conn:
            db_conn.execute(
                "UPDATE user_inventory SET is_equipped = 1 WHERE user_id = ? AND item_id = 'cosmetic_crt_scanlines'",
                (user,),
            )

        cur = db_conn.cursor()
        cur.execute(
            "SELECT is_equipped FROM user_inventory WHERE user_id = ? AND item_id = 'cosmetic_crt_scanlines'",
            (user,),
        )
        assert cur.fetchone()[0] == 1

    def test_t3_2_earn_buy_gift_verify_aurelia_bond(self, db_conn):
        """Earn gold from challenge -> Buy Starflower Tea -> Consume/gift -> Verify bond progression."""
        user = "usr-t3-2"
        # 1. Earn 100g
        credit_sqlite_gold(db_conn, user, 100)

        # 2. Buy Starflower Tea (80g)
        res = execute_sqlite_purchase(db_conn, user, "gift_starflower_tea", 1)
        assert res.new_balance == 20

        # 3. Present gift to Aurelia (consume unit)
        use_res = use_sqlite_item(db_conn, user, "gift_starflower_tea")
        assert use_res.effect_applied == "aurelia_gift"
        assert use_res.details["bond_points"] == 15
        assert use_res.details["emotion"] == "smiling_warmly"
        assert use_res.remaining_quantity == 0

    def test_t3_3_earn_buy_streak_freeze_miss_day_verify_shield(self, db_conn):
        """Earn 150g -> Buy Elixir of Frozen Time -> Miss day -> Shield protects streak."""
        user = "usr-t3-3"
        credit_sqlite_gold(db_conn, user, 150)
        execute_sqlite_purchase(db_conn, user, "consumable_streak_freeze", 1)

        # Consume item to arm freeze
        use_sqlite_item(db_conn, user, "consumable_streak_freeze")

        # Simulate missed day (delta == 2)
        now = datetime.now(UTC).date()
        two_days_ago = (now - timedelta(days=2)).isoformat()
        streak = {
            "current_streak": 10,
            "longest_streak": 10,
            "last_active_date": two_days_ago,
            "streak_freeze_count": 1,
        }
        protected = evaluate_srs_streak_freeze(streak, now)
        assert protected["current_streak"] == 10
        assert protected["streak_freeze_count"] == 0
        assert protected["streak_freeze_consumed"] is True

    def test_t3_4_multi_category_purchases(self, db_conn):
        """Purchase items across all three categories in sequence."""
        user = "usr-t3-4"
        credit_sqlite_gold(db_conn, user, 500)

        # Consumable (75g Hint Scroll)
        execute_sqlite_purchase(db_conn, user, "consumable_hint_scroll", 1)
        # Cosmetic (200g CRT Shader)
        execute_sqlite_purchase(db_conn, user, "cosmetic_crt_scanlines", 1)
        # Companion Gift (80g Starflower Tea)
        execute_sqlite_purchase(db_conn, user, "gift_starflower_tea", 1)

        # Remaining: 500 - 355 = 145g
        assert get_sqlite_currency(db_conn, user).gold == 145

        cur = db_conn.cursor()
        cur.execute("SELECT COUNT(*) FROM user_inventory WHERE user_id = ?", (user,))
        assert cur.fetchone()[0] == 3

    def test_t3_5_cross_user_dual_mode_isolation(self, db_conn):
        """Ensure guest mode and authenticated mode user data do not collide."""
        guest_id = "sandbox-user-id"
        auth_id = "firebase-jwt-uid-99"

        credit_sqlite_gold(db_conn, guest_id, 100)
        credit_sqlite_gold(db_conn, auth_id, 800)

        execute_sqlite_purchase(db_conn, guest_id, "consumable_hint_scroll", 1)
        execute_sqlite_purchase(db_conn, auth_id, "gift_elixir_pendant", 1)

        assert get_sqlite_currency(db_conn, guest_id).gold == 25
        assert get_sqlite_currency(db_conn, auth_id).gold == 300


# ============================================================================
# TIER 4: REAL-WORLD SCENARIOS (LEARNER JOURNEYS)
# ============================================================================


class TestTier4RealWorldScenarios:
    @pytest.fixture
    def db_conn(self):
        conn = sqlite3.connect(":memory:")
        create_sqlite_store_tables(conn)
        yield conn
        conn.close()

    def test_t4_1_scenario_1_the_novice_wayfarer(self, db_conn):
        """Scenario 1: Start 0g -> Solve reviews -> Unaffordable rejection -> Buy affordable."""
        user = "novice-learner"

        # 1. Start with 0g
        assert get_sqlite_currency(db_conn, user).gold == 0

        # 2. Complete 1 Easy (+35g), 1 Good (+25g), 1 Hard (+15g) = 75g
        credit_sqlite_gold(db_conn, user, 35)
        credit_sqlite_gold(db_conn, user, 25)
        credit_sqlite_gold(db_conn, user, 15)
        assert get_sqlite_currency(db_conn, user).gold == 75

        # 3. Attempt to buy Elixir of Frozen Time (150g) -> Rejected
        with pytest.raises(ValueError, match="Insufficient gold balance"):
            execute_sqlite_purchase(db_conn, user, "consumable_streak_freeze", 1)
        assert get_sqlite_currency(db_conn, user).gold == 75

        # 4. Buy Archivist's Hint Scroll (75g) -> Succeeded
        res = execute_sqlite_purchase(db_conn, user, "consumable_hint_scroll", 1)
        assert res.new_balance == 0
        assert res.inventory_item.item_id == "consumable_hint_scroll"

    def test_t4_2_scenario_2_the_guardians_devotion(self, db_conn):
        """Scenario 2: Complete challenge + reviews -> Buy Shawl -> Gift to Aurelia."""
        user = "guardian-user"

        # 1. Earn 100g (challenge) + 3 Good reviews (75g) = 175g
        credit_sqlite_gold(db_conn, user, 100)
        for _ in range(3):
            credit_sqlite_gold(db_conn, user, 25)
        assert get_sqlite_currency(db_conn, user).gold == 175

        # 2. Buy Embroidered Silver Shawl (150g) -> Balance 25g
        res = execute_sqlite_purchase(db_conn, user, "gift_silk_shawl", 1)
        assert res.new_balance == 25

        # 3. Present gift to Princess Aurelia
        use_res = use_sqlite_item(db_conn, user, "gift_silk_shawl")
        assert use_res.effect_applied == "aurelia_gift"
        assert use_res.details["bond_points"] == 30
        assert use_res.details["emotion"] == "smiling_warmly"

        # Inventory depleted
        cur = db_conn.cursor()
        cur.execute("SELECT COUNT(*) FROM user_inventory WHERE user_id = ?", (user,))
        assert cur.fetchone()[0] == 0

    def test_t4_3_scenario_3_the_spire_architect(self, db_conn):
        """Scenario 3: Intensive study -> Streak freeze -> Unaffordable theme -> Earn -> Buy theme."""
        user = "spire-architect"

        # 1. Study: 5 Good reviews (125g) + Challenge (100g) = 225g
        for _ in range(5):
            credit_sqlite_gold(db_conn, user, 25)
        credit_sqlite_gold(db_conn, user, 100)
        assert get_sqlite_currency(db_conn, user).gold == 225

        # 2. Buy Streak Freeze (150g) -> Balance 75g
        res1 = execute_sqlite_purchase(db_conn, user, "consumable_streak_freeze", 1)
        assert res1.new_balance == 75

        # 3. Consume freeze
        use_sqlite_item(db_conn, user, "consumable_streak_freeze")

        # 4. Attempt to buy Amber Theme (250g) with 75g -> Rejected
        with pytest.raises(ValueError, match="Insufficient gold balance"):
            execute_sqlite_purchase(db_conn, user, "cosmetic_theme_amber", 1)
        assert get_sqlite_currency(db_conn, user).gold == 75

        # 5. Earn 175g (5 Easy reviews x 35g) -> 75 + 175 = 250g
        for _ in range(5):
            credit_sqlite_gold(db_conn, user, 35)
        assert get_sqlite_currency(db_conn, user).gold == 250

        # 6. Buy Amber Theme (250g) -> Success!
        res2 = execute_sqlite_purchase(db_conn, user, "cosmetic_theme_amber", 1)
        assert res2.new_balance == 0
        assert res2.inventory_item.item_id == "cosmetic_theme_amber"