# src/api/routes/tasks.py
from fastapi import APIRouter, HTTPException
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
from typing import Optional
from src.core.task_manager import TaskManager

router = APIRouter(prefix="/api/v1/tasks")


class TaskStatusResponse(BaseModel):
    task_id: str
    status: str
    progress: int
    current_stage: Optional[str]
    created_at: str
    updated_at: str
    completed_at: Optional[str]


class TaskResultResponse(BaseModel):
    task_id: str
    status: str
    result: Optional[dict]
    error: Optional[dict]


@router.get("/{task_id}")
async def get_task_status(task_id: str):
    task_manager = TaskManager()
    task = await task_manager.get_task(task_id)
    if not task:
        raise HTTPException(status_code=404, detail="Task not found")
    return TaskStatusResponse(
        task_id=task.id,
        status=task.status,
        progress=100 if task.status == "completed" else 0,
        current_stage=task.status,
        created_at=task.created_at.isoformat() if task.created_at else "",
        updated_at=task.updated_at.isoformat() if task.updated_at else "",
        completed_at=task.completed_at.isoformat() if task.completed_at else None
    )


@router.get("/{task_id}/result")
async def get_task_result(task_id: str):
    task_manager = TaskManager()
    task = await task_manager.get_task(task_id)
    if not task:
        raise HTTPException(status_code=404, detail="Task not found")
    if task.status == "failed":
        return TaskResultResponse(task_id=task.id, status=task.status, result=None, error=task.error)
    return TaskResultResponse(
        task_id=task.id,
        status=task.status,
        result={"message_id": f"msg_{task.id}", "content": {"type": "text", "text": "任务结果"}, "trace_id": f"trace_{task.id}"},
        error=None
    )


@router.get("/{task_id}/stream")
async def stream_task_progress(task_id: str):
    async def event_generator():
        import asyncio
        import json
        events = [
            {"type": "started", "task_id": task_id, "estimated_seconds": 5},
            {"type": "progress", "stage": "processing", "progress": 50},
            {"type": "completed", "task_id": task_id, "result": {}}
        ]
        for event in events:
            yield f"event: {event['type']}\ndata: {json.dumps(event)}\n\n"
            await asyncio.sleep(0.1)
    return StreamingResponse(event_generator(), media_type="text/event-stream")
