# [DEF:BackendRouteShot:Module]
# @TIER: STANDARD
# @SEMANTICS: Route, Task, API, Async
# @PURPOSE: Reference implementation of a task-based route using GRACE-Poly.
# @LAYER: Interface (API)
# @RELATION: IMPLEMENTS -> [DEF:Std:API_FastAPI]
# @INVARIANT: TaskManager must be available in dependency graph.

from typing import Dict, Any
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel
from ...core.logger import belief_scope
from ...core.task_manager import TaskManager, Task
from ...core.config_manager import ConfigManager
from ...dependencies import get_task_manager, get_config_manager, get_current_user

router = APIRouter()

class CreateTaskRequest(BaseModel):
    plugin_id: str
    params: Dict[str, Any]

@router.post("/tasks", response_model=Task, status_code=status.HTTP_201_CREATED)
# [DEF:create_task:Function]
# @PURPOSE: Create and start a new task using TaskManager. Non-blocking.
# @PARAM: request (CreateTaskRequest) - Plugin and params.
# @PARAM: task_manager (TaskManager) - Async task executor.
# @PRE: plugin_id must match a registered plugin.
# @POST: A new task is spawned; Task ID returned immediately.
# @SIDE_EFFECT: Writes to DB, Trigger background worker.
async def create_task(
    request: CreateTaskRequest,
    task_manager: TaskManager = Depends(get_task_manager),
    config: ConfigManager = Depends(get_config_manager),
    current_user = Depends(get_current_user)
):
    # Context Logging
    with belief_scope("create_task"):
        try:
            # 1. Action: Configuration Resolution
            timeout = config.get("TASKS_DEFAULT_TIMEOUT", 3600)

            # 2. Action: Spawn async task
            # @RELATION: CALLS -> task_manager.create_task
            task = await task_manager.create_task(
                plugin_id=request.plugin_id,
                params={**request.params, "timeout": timeout}
            )
            return task
            
        except ValueError as e:
             # 3. Recovery: Domain logic error mapping
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST, 
                detail=str(e)
            )
        except Exception as e:
            # @UX_STATE: Error feedback -> 500 Internal Error
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, 
                detail="Internal Task Spawning Error"
            )
# [/DEF:create_task:Function]

# [/DEF:BackendRouteShot:Module]