from typing import List

from sqlmodel import select,delete
from sqlalchemy.ext.asyncio import AsyncSession
from entity.frame_analysis_result import FrameAnalysisResultCreate, FrameAnalysisResult


class FrameAnalysisResultService:

    def __init__(self, db: AsyncSession):
        self.db = db

    async def add_frame_analysis_results(self, results: List[FrameAnalysisResultCreate]):
        new_results = [FrameAnalysisResult.model_validate(result) for result in results]
        for result in new_results:
            self.db.add(result)
        await self.db.commit()
        for result in new_results:
            await self.db.refresh(result)
        return new_results

    async def get_results_by_frame(self, frame_id):
        statement = select(FrameAnalysisResult).where(FrameAnalysisResult.frame_id == frame_id)
        results = await self.db.execute(statement)
        return results.scalars().all()

    async def delete_by_frame_id(self, max_frame_id):
        statement = delete(FrameAnalysisResult).where(FrameAnalysisResult.frame_id <= max_frame_id)
        await self.db.execute(statement)
        await self.db.commit()
        return max_frame_id
