from __future__ import annotations

from fastapi import APIRouter, HTTPException

from app.storage.repository import Repository


router = APIRouter(prefix="/tasks", tags=["tasks"])
repository = Repository()


def _task_response(row: dict) -> dict:
    return {
        "taskId": row["id"],
        "type": row["type"],
        "appId": row["app_id"],
        "appName": row["app_name"],
        "status": row["status"],
        "progress": row["progress"],
        "currentStep": row["current_step"],
        "currentComponentId": row["current_component_id"],
        "errorMessage": row["error_message"],
        "createdAt": row["created_at"],
        "startedAt": row["started_at"],
        "finishedAt": row["finished_at"],
    }


@router.get("/{task_id}")
def get_task(task_id: str) -> dict:
    task = repository.get_task(task_id)
    if not task:
        raise HTTPException(status_code=404, detail="Task not found")
    return _task_response(task)


@router.get("/{task_id}/logs")
def get_task_logs(task_id: str) -> dict:
    if not repository.get_task(task_id):
        raise HTTPException(status_code=404, detail="Task not found")
    return {
        "taskId": task_id,
        "logs": [
            {
                "time": item["timestamp"],
                "level": item["level"],
                "message": item["message"],
            }
            for item in repository.get_task_logs(task_id)
        ],
    }


@router.get("/{task_id}/components")
def get_task_components(task_id: str) -> dict:
    if not repository.get_task(task_id):
        raise HTTPException(status_code=404, detail="Task not found")
    return {
        "taskId": task_id,
        "components": [
            {
                "componentId": item["component_id"],
                "type": item["type"],
                "status": item["status"],
                "progress": item["progress"],
                "currentStep": item["current_step"],
                "errorMessage": item["error_message"],
                "serviceCheckStatus": item["service_check_status"],
                "serviceChecks": item["service_checks"],
                "startedAt": item["started_at"],
                "finishedAt": item["finished_at"],
            }
            for item in repository.get_task_components(task_id)
        ],
    }
