import os
import time
import uuid
from typing import Optional, List
from fastapi import APIRouter, UploadFile, File, Response
from app.schemas.analyze import Analyze, AnalyzeData
from app.services.model import TaskStatus, TaskStore

router = APIRouter()


@router.post("/analyze")
async def submit_analyze(response: Response, images: Optional[List[UploadFile]] = File(default=[])):
    from app.main import UPLOAD_DIR, WORKER
    if not images:
        response.status_code = 400
        return Analyze(
            success=False,
            data=AnalyzeData(
                taskId="",
                status=TaskStatus.FAILED.name,
                message="请上传图片",
                estimatedTime="",
                filesReceived=0
            )
        )

    task_id = f"task_{int(time.time() * 1000)}_{uuid.uuid4().hex[:10]}"

    task_dir = os.path.join(UPLOAD_DIR, task_id, "inputs")
    os.makedirs(task_dir, exist_ok=True)

    saved_paths = []
    if images:
        for idx, img in enumerate(images):
            ext = os.path.splitext(img.filename)[1]
            file_path = os.path.join(task_dir, f"{idx}{ext}")
            with open(file_path, "wb") as f:
                f.write(await img.read())
            saved_paths.append(file_path)

    WORKER.task_store[task_id] = TaskStore(images=saved_paths)
    WORKER.task_queue.put(task_id)

    return Analyze(
        success=True,
        data=AnalyzeData(
            taskId=task_id,
            status=TaskStatus.QUEUED.name,
            message=f"已提交 {len(saved_paths)} 张图片，正在分析",
            estimatedTime="",
            filesReceived=len(saved_paths)
        )
    )
