"""Worlds routes: CRUD + world builder flow.""" from __future__ import annotations from typing import List from uuid import UUID from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from fastapi import APIRouter, Depends, HTTPException from app.db import get_db_dep from app.deps import get_current_user from app.engine.world_builder import commit_world_builder, continue_world_builder, start_world_builder from app.engine.world_editor import edit_world_via_chat, reset_editor_dialogue from app.models import User, World from app.schemas import ( WorldBuilderCommit, WorldBuilderMessage, WorldBuilderReply, WorldBuilderStart, WorldCreate, WorldEditorChatReply, WorldEditorChatRequest, WorldOut, WorldUpdate, ) router = APIRouter(prefix="/api/worlds", tags=["worlds"]) @router.get("", response_model=List[WorldOut]) async def list_worlds( db: AsyncSession = Depends(get_db_dep), user: User = Depends(get_current_user), ): result = await db.execute( select(World).where(World.owner_id == user.id).order_by(World.updated_at.desc()) ) return result.scalars().all() @router.get("/{world_id}", response_model=WorldOut) async def get_world( world_id: UUID, db: AsyncSession = Depends(get_db_dep), user: User = Depends(get_current_user), ): result = await db.execute(select(World).where(World.id == world_id)) world = result.scalars().first() if not world: raise HTTPException(status_code=404, detail="world_not_found") if world.owner_id != user.id and not user.is_admin: raise HTTPException(status_code=403, detail="forbidden") return world @router.post("", response_model=WorldOut, status_code=201) async def create_world( payload: WorldCreate, db: AsyncSession = Depends(get_db_dep), user: User = Depends(get_current_user), ): world = World( owner_id=user.id, name=payload.name, language=payload.language, definition={}, state={}, status="draft", preset_id=payload.preset_id, ) db.add(world) await db.commit() await db.refresh(world) return world @router.patch("/{world_id}", response_model=WorldOut) async def update_world( world_id: UUID, payload: WorldUpdate, db: AsyncSession = Depends(get_db_dep), user: User = Depends(get_current_user), ): result = await db.execute(select(World).where(World.id == world_id)) world = result.scalars().first() if not world: raise HTTPException(status_code=404, detail="world_not_found") if world.owner_id != user.id and not user.is_admin: raise HTTPException(status_code=403, detail="forbidden") for field, value in payload.model_dump(exclude_unset=True).items(): setattr(world, field, value) await db.commit() await db.refresh(world) return world @router.delete("/{world_id}", status_code=204) async def delete_world( world_id: UUID, db: AsyncSession = Depends(get_db_dep), user: User = Depends(get_current_user), ): result = await db.execute(select(World).where(World.id == world_id)) world = result.scalars().first() if not world: raise HTTPException(status_code=404, detail="world_not_found") if world.owner_id != user.id and not user.is_admin: raise HTTPException(status_code=403, detail="forbidden") await db.delete(world) await db.commit() # === World Builder flow === @router.post("/builder/start", response_model=WorldBuilderReply) async def builder_start( payload: WorldBuilderStart, db: AsyncSession = Depends(get_db_dep), user: User = Depends(get_current_user), ): try: return await start_world_builder( db=db, user=user, world_name=payload.world_name, language=payload.language, preset_id=payload.preset_id, setting_brief=payload.setting_brief, character_brief=payload.character_brief, rules_brief=payload.rules_brief, notes=payload.notes, ) except Exception as e: raise HTTPException(status_code=500, detail=f"builder_start_failed: {e}") @router.post("/builder/continue", response_model=WorldBuilderReply) async def builder_continue( payload: WorldBuilderMessage, db: AsyncSession = Depends(get_db_dep), user: User = Depends(get_current_user), ): try: return await continue_world_builder(db=db, user=user, session_id=payload.session_id, user_message=payload.message) except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) except Exception as e: raise HTTPException(status_code=500, detail=f"builder_continue_failed: {e}") @router.post("/builder/commit", response_model=WorldOut) async def builder_commit( payload: WorldBuilderCommit, db: AsyncSession = Depends(get_db_dep), user: User = Depends(get_current_user), ): try: return await commit_world_builder(db=db, user=user, session_id=payload.session_id, name=payload.name) except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) except Exception as e: raise HTTPException(status_code=500, detail=f"builder_commit_failed: {e}") # === World Editor (AI-assisted editing of an existing world) === @router.post("/{world_id}/chat", response_model=WorldEditorChatReply) async def world_editor_chat( world_id: UUID, payload: WorldEditorChatRequest, db: AsyncSession = Depends(get_db_dep), user: User = Depends(get_current_user), ): """Chat with the AI to edit an existing world's definition. Returns the AI's prose reply plus the proposed new definition. The frontend must call PATCH /worlds/{id} to actually persist the change. """ result = await db.execute(select(World).where(World.id == world_id)) world = result.scalars().first() if not world: raise HTTPException(status_code=404, detail="world_not_found") if world.owner_id != user.id and not user.is_admin: raise HTTPException(status_code=403, detail="forbidden") try: ai_message, new_defn, changed = await edit_world_via_chat( db=db, user=user, world=world, message=payload.message, ) except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) except Exception as e: raise HTTPException(status_code=500, detail=f"world_editor_chat_failed: {e}") return WorldEditorChatReply( ai_message=ai_message, definition=new_defn, changed=changed, ) @router.post("/{world_id}/chat/reset") async def world_editor_chat_reset( world_id: UUID, db: AsyncSession = Depends(get_db_dep), user: User = Depends(get_current_user), ): """Clear the cached editor dialogue for a world (start fresh).""" result = await db.execute(select(World).where(World.id == world_id)) world = result.scalars().first() if not world: raise HTTPException(status_code=404, detail="world_not_found") if world.owner_id != user.id and not user.is_admin: raise HTTPException(status_code=403, detail="forbidden") reset_editor_dialogue(world_id) return {"ok": True}