from fastapi import APIRouter, Depends, HTTPException from pydantic import BaseModel from typing import Optional from app.services.page_service import PageService from app.database.sqlite_db import get_db, SQLiteDB router = APIRouter(prefix="/reference", tags=["Reference"]) class ReferenceLookupRequest(BaseModel): vol: int page: int type: str # 'footnote' | 'abbrev' id: str context: Optional[str] = None def get_page_service(db: SQLiteDB = Depends(get_db)) -> PageService: return PageService(db) @router.get("/lookup") async def lookup_reference( vol: int, page: int, type: str, id: str, service: PageService = Depends(get_page_service), ): if type == "footnote": content = service.get_footnote(vol, page, id) if not content: return {"content": "ไม่พบข้อมูลเชิงอรรถนี้บนหน้าเว็บปัจจุบัน", "found": False} return {"content": content, "found": True} elif type == "abbrev": # Query DB directly — no LLM or RAG service needed (all abbrevs pre-indexed) import json, re clean_id = re.sub(r'[()\[\]-]', '', id).strip() lookup_id = "_default" if clean_id and re.match(r'^[\u0E50-\u0E59\d]+$', clean_id): lookup_id = clean_id with service.db.get_connection() as conn: cursor = conn.cursor() cursor.execute(""" SELECT content FROM reference_markers WHERE volume_num = ? AND page_num = ? AND marker_id = ? AND type = 'abbrev' """, (vol, page, lookup_id)) row = cursor.fetchone() if row: content = row["content"] if content.startswith('['): try: entries = json.loads(content) if isinstance(entries, list): if entries and isinstance(entries[0], str): return {"content": "\n\n".join(entries), "found": True} parts = [e.get("expansion", "") for e in entries if isinstance(e, dict) and e.get("expansion", "")] if parts: return {"content": "\n\n".join(parts), "found": True} except (json.JSONDecodeError, TypeError, AttributeError): pass return {"content": content, "found": True} return {"content": content, "found": True} return {"content": f"(ย่อ) — ยังไม่มีข้อมูลขยายความในฐานข้อมูลเล่ม {vol} หน้า {page}", "found": False} else: raise HTTPException(status_code=400, detail="Invalid reference type")