import os
import uuid
from datetime import datetime

import aiofiles
import cv2
from sqlalchemy.ext.asyncio import AsyncSession

from entity.alarm_record import AlarmRecordCreate, AlarmRecord


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

    async def add_alarm(self, alarm_data:AlarmRecordCreate, alarm_np_img):
        async def save_alarm_file():
            # 生成当前年月日作为目录路径
            current_date = datetime.now().strftime('%Y-%m-%d')
            # 生成随机 UUID 作为文件名
            file_name = f"{uuid.uuid4()}.jpeg"
            # 创建保存图片的完整路径
            save_path = os.path.join('./storage/alarms', current_date, file_name)
            # 创建目录（如果不存在）
            os.makedirs(os.path.dirname(save_path), exist_ok=True)

            # 将 frame_data 转换为二进制数据（假设 frame_data 是一个 numpy 数组）
            _, encoded_image = cv2.imencode('.jpeg', alarm_np_img)
            image_data = encoded_image.tobytes()

            # 使用 aiofiles 进行异步写入
            async with aiofiles.open(save_path, 'wb') as f:
                await f.write(image_data)

            return save_path

        # 异步保存图片文件
        alarm_img_path = await save_alarm_file()

        # 创建并保存到数据库中
        alarm_record = AlarmRecord.model_validate(alarm_data)
        alarm_record.alarm_image = alarm_img_path
        self.db.add(alarm_record)
        await self.db.commit()
        await self.db.refresh(alarm_record)
        return alarm_record
