"""Work log REST API routes."""

from fastapi import APIRouter, Depends, HTTPException, Query, Request

from peon_mcp.common.auth import AuthInfo, get_auth
from peon_mcp.common.dependencies import get_db, get_project_id
from peon_mcp.common.schemas import PaginatedResponse
from peon_mcp.common.scoping import authorize_project_access, authorize_entity_project_access
from peon_mcp.db import row_to_dict
from peon_mcp.work_logs.schemas import CreateWorkLogRequest, WorkLogResponse

router = APIRouter(tags=["Work Logs"])


@router.get("/api/projects/{owner}/{repo}/logs", response_model=PaginatedResponse[WorkLogResponse])
async def list_work_logs(
    request: Request,
    limit: int = Query(default=50, ge=1, le=200),
    offset: int = Query(default=0, ge=0),
    project_id: str = Depends(get_project_id),
    auth: AuthInfo = Depends(get_auth),
    db=Depends(get_db),
):
    await authorize_project_access(db, auth, project_id, request)

    # Get total count for pagination metadata
    count_rows = await db.execute_fetchall(
        "SELECT COUNT(*) FROM work_logs WHERE project_id = ?",
        (project_id,),
    )
    total = count_rows[0]["count"] if count_rows else 0

    rows = await db.execute_fetchall(
        "SELECT * FROM work_logs WHERE project_id = ? ORDER BY created_at DESC LIMIT ? OFFSET ?",
        (project_id, limit, offset),
    )
    items = [row_to_dict(r) for r in rows]

    return {
        "items": items,
        "total": total,
        "limit": limit,
        "offset": offset,
        "has_next": (offset + len(items)) < total,
    }


@router.get("/api/tasks/{task_id}/logs", response_model=list[WorkLogResponse])
async def list_task_work_logs(
    task_id: int,
    request: Request,
    auth: AuthInfo = Depends(get_auth),
    db=Depends(get_db),
):
    """List work logs for a specific task."""
    await authorize_entity_project_access(db, auth, request, "tasks", task_id)

    rows = await db.execute_fetchall(
        "SELECT * FROM work_logs WHERE task_id = ? ORDER BY created_at DESC",
        (task_id,),
    )
    return [row_to_dict(r) for r in rows]


@router.post("/api/projects/{owner}/{repo}/logs", response_model=WorkLogResponse, status_code=201)
async def create_work_log(
    body: CreateWorkLogRequest,
    request: Request,
    project_id: str = Depends(get_project_id),
    auth: AuthInfo = Depends(get_auth),
    db=Depends(get_db),
):
    await authorize_project_access(db, auth, project_id, request)

    task_id = body.task_id
    summary = body.summary.strip()
    if not summary:
        raise HTTPException(400, detail="summary is required")
    task_rows = await db.execute_fetchall("SELECT id FROM tasks WHERE id = ?", (task_id,))
    if not task_rows:
        raise HTTPException(404, detail=f"Task {task_id} not found")
    project_rows = await db.execute_fetchall("SELECT id FROM projects WHERE id = ?", (project_id,))
    if not project_rows:
        raise HTTPException(404, detail=f"Project {project_id!r} not found")
    cursor = await db.execute(
        "INSERT INTO work_logs (task_id, project_id, summary, files_changed, test_result) VALUES (?, ?, ?, ?, ?) RETURNING id",
        (task_id, project_id, summary, body.files_changed, body.test_result),
    )
    new_id = cursor.lastrowid
    await db.commit()
    rows = await db.execute_fetchall(
        "SELECT * FROM work_logs WHERE id = ?", (new_id,)
    )
    return row_to_dict(rows[0])
