"""Store & Inventory Router for AlgoSpaced OS. Handles player currency balances, 12-item catalog, atomic purchase transactions, inventory item consumption, cosmetic equipping, and transaction history. """ import asyncio import logging from datetime import UTC, datetime from enum import StrEnum from typing import Any, Literal from fastapi import APIRouter, Depends, HTTPException, status from pydantic import BaseModel, Field import db from core.auth import Client, get_auth_session from sandbox_db import InsufficientFundsError, ItemNotFoundError logger = logging.getLogger("algospaced") router = APIRouter(tags=["store"]) # ============================================================================== # Domain Enums & Pydantic Models # ============================================================================== class StoreItemCategory(StrEnum): CONSUMABLE = "consumable" COSMETIC = "cosmetic" COMPANION_GIFT = "companion_gift" class StoreItemEffectType(StrEnum): STREAK_FREEZE = "streak_freeze" HINT_SCROLL = "hint_scroll" FOCUS_BOOST = "focus_boost" WALLPAPER = "wallpaper" CRT_THEME = "crt_theme" PALETTE_THEME = "palette_theme" AURELIA_GIFT = "aurelia_gift" class PlayerCurrency(BaseModel): gold: int = Field(default=0, ge=0, description="Current spendable gold balance") lifetime_earned: int = Field(default=0, ge=0, description="Total gold earned across all time") updated_at: str = Field(description="ISO 8601 timestamp of last currency mutation") class StoreItem(BaseModel): id: str name: str category: StoreItemCategory price: int = Field(gt=0, description="Price in gold, must be positive integer") lore: str icon: str effect_type: StoreItemEffectType effect_payload: dict[str, Any] = Field(default_factory=dict) class InventoryItem(BaseModel): item_id: str quantity: int = Field(default=1, ge=0, description="Owned quantity of item") is_equipped: bool = Field( default=False, description="Whether cosmetic item is actively equipped" ) acquired_at: str = Field(description="ISO 8601 timestamp when item was first acquired") updated_at: str = Field(description="ISO 8601 timestamp of last inventory update") class StoreTransaction(BaseModel): id: str user_id: str item_id: str item_name: str price: int = Field(ge=0) quantity: int = Field(ge=1) total_price: int = Field(ge=0) balance_after: int = Field(ge=0) status: Literal["completed", "failed"] timestamp: str # ============================================================================== # Request and Response Models # ============================================================================== class PurchaseItemRequest(BaseModel): item_id: str quantity: int = Field(default=1, ge=1, description="Quantity to purchase (minimum 1)") class PurchaseItemResponse(BaseModel): success: bool = True item: StoreItem new_balance: int = Field(ge=0) inventory_item: InventoryItem class UseItemRequest(BaseModel): item_id: str class UseItemResponse(BaseModel): success: bool = True 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 = True item_id: str is_equipped: bool # ============================================================================== # Canonical 12-Item Store Catalog # ============================================================================== STORE_CATALOG: list[StoreItem] = [ # 1. Study Consumables StoreItem( id="consumable_streak_freeze", name="Elixir of Frozen Time", category=StoreItemCategory.CONSUMABLE, price=150, lore="A crystalline phial filled with the enchanted sands of Chronos, arresting the relentless march of time when darkness falls.", icon="ShieldAlert", effect_type=StoreItemEffectType.STREAK_FREEZE, effect_payload={"freeze_charges": 1}, ), StoreItem( id="consumable_hint_scroll", name="Archivist's Hint Scroll", category=StoreItemCategory.CONSUMABLE, price=75, lore="An illuminated vellum scroll penned by royal archivists, unravelling algorithmic intuition and pattern landmarks.", icon="Scroll", effect_type=StoreItemEffectType.HINT_SCROLL, effect_payload={"hint_tokens": 1}, ), StoreItem( id="consumable_focus_draught", name="Potion of Keen Insight", category=StoreItemCategory.CONSUMABLE, price=100, lore="A sparkling azure potion that heightens mental acuity and doubles gold earned on your next 3 completed review cards.", icon="Sparkles", effect_type=StoreItemEffectType.FOCUS_BOOST, effect_payload={"multiplier": 2, "reviews_remaining": 3}, ), StoreItem( id="consumable_campfire_stew", name="Hearty Wayfarer's Stew", category=StoreItemCategory.CONSUMABLE, price=50, lore="A steaming bowl of herbal root stew prepared over the campfire coals, dispelling mental fatigue and restoring composure.", icon="Flame", effect_type=StoreItemEffectType.FOCUS_BOOST, effect_payload={"fatigue_reset": True}, ), # 2. Desktop Cosmetics StoreItem( id="cosmetic_crt_scanlines", name="Arcade CRT Phosphor Shader", category=StoreItemCategory.COSMETIC, price=200, lore="A retro cathode-ray raster filter with nostalgic scanlines, curved CRT edge vignette, and vintage phosphor bloom.", icon="Tv", effect_type=StoreItemEffectType.CRT_THEME, effect_payload={"overlay_class": "crt-scanlines-active"}, ), StoreItem( id="cosmetic_theme_amber", name="Amber Campfire Theme", category=StoreItemCategory.COSMETIC, price=250, lore="A cozy UI palette featuring warm ember golds, toasted parchment backgrounds, and rustic brass window borders.", icon="Flame", effect_type=StoreItemEffectType.PALETTE_THEME, effect_payload={"theme_id": "amber"}, ), StoreItem( id="cosmetic_theme_cyber", name="Synthwave Spire Theme", category=StoreItemCategory.COSMETIC, price=300, lore="Electric neon magenta and cyan hues inspired by the luminous power conduits pulsing beneath the ancient tower.", icon="Cpu", effect_type=StoreItemEffectType.PALETTE_THEME, effect_payload={"theme_id": "cyber"}, ), StoreItem( id="cosmetic_wallpaper_sanctuary", name="Sanctuary of the Elixir", category=StoreItemCategory.COSMETIC, price=350, lore="A high-resolution landscape of the distant Ancient Tower glowing beneath the celestial northern aurora.", icon="Image", effect_type=StoreItemEffectType.WALLPAPER, effect_payload={"wallpaper_url": "/wallpapers/sanctuary_spire.webp"}, ), # 3. Companion Gifts StoreItem( id="gift_starflower_tea", name="Soothing Starflower Tea", category=StoreItemCategory.COMPANION_GIFT, price=80, lore="Delicate white alpine blossoms harvested from mountain ridges, brewed into a soothing remedy that cools high fevers.", icon="Flower2", effect_type=StoreItemEffectType.AURELIA_GIFT, effect_payload={"bond_points": 15, "emotion": "smiling_warmly"}, ), StoreItem( id="gift_silk_shawl", name="Embroidered Silver Shawl", category=StoreItemCategory.COMPANION_GIFT, price=150, lore="A lightweight yet luxuriously warm shawl woven from palace silk and lined with silver thread to fend off freezing winds.", icon="Shirt", effect_type=StoreItemEffectType.AURELIA_GIFT, effect_payload={"bond_points": 30, "emotion": "smiling_warmly"}, ), StoreItem( id="gift_music_box", name="Celestial Music Box", category=StoreItemCategory.COMPANION_GIFT, price=300, lore="A miniature brass music box that softly plays the lullaby of her childhood palace gardens.", icon="Music", effect_type=StoreItemEffectType.AURELIA_GIFT, effect_payload={"bond_points": 60, "emotion": "excited_expression"}, ), StoreItem( id="gift_elixir_pendant", name="Glimmer of the Sanctuary", category=StoreItemCategory.COMPANION_GIFT, price=500, lore="A carved crystalline teardrop imbued with starlight from the summit of the Ancient Tower.", icon="Gem", effect_type=StoreItemEffectType.AURELIA_GIFT, effect_payload={"bond_points": 100, "emotion": "excited_expression"}, ), ] # Canonical lookup index + aliases STORE_CATALOG_MAP: dict[str, StoreItem] = {item.id: item for item in STORE_CATALOG} # Friendly aliases _ALIASES = { "streak_freeze": "consumable_streak_freeze", "hint_scroll": "consumable_hint_scroll", "focus_potion": "consumable_focus_draught", "focus_draught": "consumable_focus_draught", "coffee_brew": "consumable_campfire_stew", "campfire_stew": "consumable_campfire_stew", "crt_amber_phosphor": "cosmetic_crt_scanlines", "crt_scanlines": "cosmetic_crt_scanlines", "theme_amber": "cosmetic_theme_amber", "theme_cyber": "cosmetic_theme_cyber", "theme_fantasy_dungeon": "cosmetic_theme_cyber", "wallpaper_royal_library": "cosmetic_wallpaper_sanctuary", "wallpaper_celestial_citadel": "cosmetic_wallpaper_sanctuary", "wallpaper_sanctuary": "cosmetic_wallpaper_sanctuary", "gift_royal_tea": "gift_starflower_tea", "starflower_tea": "gift_starflower_tea", "gift_quill": "gift_silk_shawl", "silk_shawl": "gift_silk_shawl", "music_box": "gift_music_box", "gift_celestial_globe": "gift_elixir_pendant", "elixir_pendant": "gift_elixir_pendant", } for alias_key, target_id in _ALIASES.items(): if target_id in STORE_CATALOG_MAP and alias_key not in STORE_CATALOG_MAP: STORE_CATALOG_MAP[alias_key] = STORE_CATALOG_MAP[target_id] # ============================================================================== # REST API Endpoints # ============================================================================== @router.get("/api/currency", response_model=PlayerCurrency) async def get_currency(client: Client = Depends(get_auth_session)): """Retrieves the player's current gold balance and lifetime earned gold.""" currency_data = await asyncio.to_thread(db.get_user_currency, client) if not currency_data: currency_data = { "gold": 0, "lifetime_earned": 0, "updated_at": datetime.now(UTC).isoformat(), } return PlayerCurrency(**currency_data) @router.get("/api/store/items", response_model=list[StoreItem]) async def get_store_items(client: Client = Depends(get_auth_session)): """Returns the complete 12-item store catalog.""" return STORE_CATALOG @router.get("/api/inventory", response_model=list[InventoryItem]) async def get_inventory(client: Client = Depends(get_auth_session)): """Returns all items currently held in the player's inventory.""" items = await asyncio.to_thread(db.get_user_inventory, client) return [InventoryItem(**item) for item in items] @router.post("/api/store/purchase", response_model=PurchaseItemResponse) async def purchase_store_item(req: PurchaseItemRequest, client: Client = Depends(get_auth_session)): """ Executes an atomic store purchase. Validates balance, deducts price, credits inventory, logs transaction. """ if req.quantity <= 0: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Purchase quantity must be at least 1.", ) item = STORE_CATALOG_MAP.get(req.item_id) if not item: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Store item '{req.item_id}' not found.", ) try: result = await asyncio.to_thread( db.purchase_store_item, item.model_dump(), req.quantity, client ) except InsufficientFundsError: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Insufficient gold balance to purchase item.", ) except ValueError as e: if "insufficient" in str(e).lower(): raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Insufficient gold balance to purchase item.", ) raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) except Exception as e: logger.exception("Unexpected error in purchase_store_item: %s", e) raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Failed to complete store purchase.", ) return PurchaseItemResponse( success=True, item=item, new_balance=result["new_balance"], inventory_item=InventoryItem(**result["inventory_item"]), ) @router.post("/api/inventory/use", response_model=UseItemResponse) async def use_inventory_item(req: UseItemRequest, client: Client = Depends(get_auth_session)): """ Consumes a single unit of an inventory item and triggers its effect. """ item = STORE_CATALOG_MAP.get(req.item_id) if not item: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Store item '{req.item_id}' not found.", ) if item.category == StoreItemCategory.COSMETIC: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=f"Item '{req.item_id}' is a cosmetic and cannot be consumed. Use equip instead.", ) try: result = await asyncio.to_thread(db.use_inventory_item, req.item_id, client) except ItemNotFoundError: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=f"Item '{req.item_id}' is not available in inventory.", ) except Exception as e: logger.exception("Unexpected error in use_inventory_item: %s", e) raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Failed to consume inventory item.", ) return UseItemResponse( success=True, effect_applied=result.get("effect_applied", item.effect_type), remaining_quantity=result["remaining_quantity"], details=result.get("details", item.effect_payload), ) @router.post("/api/inventory/equip", response_model=EquipItemResponse) async def equip_inventory_item(req: EquipItemRequest, client: Client = Depends(get_auth_session)): """ Toggles the equipped state of a cosmetic item. """ item = STORE_CATALOG_MAP.get(req.item_id) if not item: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Store item '{req.item_id}' not found.", ) if item.category != StoreItemCategory.COSMETIC: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=f"Item '{req.item_id}' is not a cosmetic item and cannot be equipped.", ) try: result = await asyncio.to_thread( db.equip_inventory_item, req.item_id, req.is_equipped, client ) except ItemNotFoundError: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=f"Item '{req.item_id}' is not in your inventory.", ) except Exception as e: logger.exception("Unexpected error in equip_inventory_item: %s", e) raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Failed to update equip status.", ) return EquipItemResponse( success=True, item_id=req.item_id, is_equipped=result.get("is_equipped", req.is_equipped), ) @router.get("/api/store/transactions", response_model=list[StoreTransaction]) async def get_store_transactions(client: Client = Depends(get_auth_session)): """Retrieves chronological audit trail of user purchases.""" txs = await asyncio.to_thread(db.get_store_transactions, client) return [StoreTransaction(**tx) for tx in txs]