#[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
# GRACE: Правильный импорт глобального логгера и scope
from ...core.logger import logger, 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()

# [DEF:CreateTaskRequest:Class]
# @PURPOSE: DTO for task creation payload.
class CreateTaskRequest(BaseModel):
    plugin_id: str
    params: Dict[str, Any]
# [/DEF:CreateTaskRequest:Class]

# [DEF:create_task:Function]
# @PURPOSE: Create and start a new task using TaskManager. Non-blocking.
# @DATA_CONTRACT: Input -> CreateTaskRequest, Output -> Task
# @PRE: plugin_id must match a registered plugin.
# @POST: A new task is spawned; Task object returned immediately.
# @SIDE_EFFECT: Writes to DB, Triggers background worker.
#
# @UX_STATE: Success -> 201 Created
# @UX_STATE: Error(Validation) -> 400 Bad Request
# @UX_STATE: Error(System) -> 500 Internal Server Error
@router.post("/tasks", response_model=Task, status_code=status.HTTP_201_CREATED)
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)
):
    # GRACE: Открываем семантическую транзакцию
    with belief_scope("create_task"):
        try:
            # GRACE: [REASON] - Фиксируем начало дедуктивной цепочки
            logger.reason("Resolving configuration and spawning task", extra={"plugin_id": request.plugin_id})
            
            timeout = config.get("TASKS_DEFAULT_TIMEOUT", 3600)

            # @RELATION: CALLS -> task_manager.create_task
            task = await task_manager.create_task(
                plugin_id=request.plugin_id,
                params={**request.params, "timeout": timeout}
            )
            
            # GRACE:[REFLECT] - Подтверждаем выполнение @POST перед выходом
            logger.reflect("Task spawned successfully", extra={"task_id": task.id})
            return task
            
        except ValueError as e:
            # GRACE: [EXPLORE] - Обработка ожидаемого отклонения
            logger.explore("Domain validation error during task creation", exc_info=e)
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST, 
                detail=str(e)
            )
        except Exception as e:
            # GRACE: [EXPLORE] - Обработка критического сбоя
            logger.explore("Internal Task Spawning Error", exc_info=e)
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, 
                detail="Internal Task Spawning Error"
            )
# [/DEF:create_task:Function]

# [/DEF:BackendRouteShot:Module]