# backend/app/api/v1/endpoints/evidence.py from fastapi import APIRouter, UploadFile, File, HTTPException, status, Depends from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy import text from app.api.deps import get_db, get_current_user from app.schemas.evidence import OcrResponse from app.services.image_processor import DocumentImageProcessor from app.services.ai_ocr_service import AiOcrService router = APIRouter() @router.post("/scan-registration", response_model=OcrResponse) async def scan_registration_document( file: UploadFile = File(...), db: AsyncSession = Depends(get_db), current_user = Depends(get_current_user) ): """ Forgalmi engedély feldolgozása dinamikus, rendszer-szintű korlátok ellenőrzésével. """ try: # 1. 🔍 DINAMIKUS LIMIT LEKÉRDEZÉS (Hierarchikus system_parameters táblából) limit_query = text(""" SELECT (value->>:plan)::int FROM data.system_parameters WHERE key = 'VEHICLE_LIMIT' AND scope_level = 'global' AND is_active = true """) limit_res = await db.execute(limit_query, {"plan": current_user.subscription_plan}) max_allowed = limit_res.scalar() or 1 # Ha nincs paraméter, 1-re korlátozunk a biztonság kedvéért # 2. 📊 FELHASZNÁLÓI JÁRMŰSZÁM ELLENŐRZÉSE count_query = text("SELECT count(*) FROM data.assets WHERE operator_person_id = :p_id") current_count = (await db.execute(count_query, {"p_id": current_user.person_id})).scalar() if current_count >= max_allowed: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail=f"Csomaglimit túllépés. A jelenlegi '{current_user.subscription_plan}' csomagod max {max_allowed} járművet engedélyez." ) # 3. 📸 KÉPFELDOLGOZÁS ÉS AI OCR raw_bytes = await file.read() clean_bytes = DocumentImageProcessor.process_for_ocr(raw_bytes) if not clean_bytes: raise ValueError("A kép optimalizálása az OCR számára nem sikerült.") extracted_data = await AiOcrService.extract_registration_data(clean_bytes) return OcrResponse( success=True, message=f"Sikeres adatkivonás ({current_user.subscription_plan} csomag).", data=extracted_data ) except HTTPException as he: # FastAPI hibák továbbdobása (pl. 403 Forbidden) raise he except Exception as e: # Általános hiba kezelése korrekt indentálással raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"Robot 3 feldolgozási hiba: {str(e)}" )