"""Task instance API routes."""
from __future__ import annotations

from fastapi import APIRouter, HTTPException
from sqlalchemy import select

from crondag.models.base import get_session_factory
from crondag.models.task_instance import TaskInstanceModel
from crondag.models.log import TaskLogModel

router = APIRouter(tags=["tasks"])


@router.get("/tasks/{task_instance_id}")
async def get_task_instance(task_instance_id: int):
    """Get task instance details."""
    session_factory = get_session_factory()
    async with session_factory() as session:
        ti = await session.get(TaskInstanceModel, task_instance_id)
        if not ti:
            raise HTTPException(status_code=404, detail="Task instance not found")

        return {
            "id": ti.id,
            "task_id": ti.task_id,
            "dag_id": ti.dag_id,
            "run_id": ti.run_id,
            "state": ti.state,
            "try_number": ti.try_number,
            "max_retries": ti.max_retries,
            "start_date": str(ti.start_date),
            "end_date": str(ti.end_date),
            "duration": ti.duration,
            "return_value": ti.return_value,
            "error": ti.error,
        }


@router.get("/tasks/{task_instance_id}/logs")
async def get_task_logs(task_instance_id: int):
    """Get logs for a task instance."""
    session_factory = get_session_factory()
    async with session_factory() as session:
        ti = await session.get(TaskInstanceModel, task_instance_id)
        if not ti:
            raise HTTPException(status_code=404, detail="Task instance not found")

        result = await session.execute(
            select(TaskLogModel)
            .where(TaskLogModel.task_instance_id == task_instance_id)
            .order_by(TaskLogModel.timestamp, TaskLogModel.line_number)
        )
        logs = result.scalars().all()

        return {
            "task_id": ti.task_id,
            "dag_id": ti.dag_id,
            "run_id": ti.run_id,
            "state": ti.state,
            "logs": [
                {
                    "line": l.line_number,
                    "timestamp": str(l.timestamp),
                    "level": l.level,
                    "message": l.message,
                }
                for l in logs
            ],
        }
