from typing import Optional
from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session

from app.core.database import get_db
from app.models.user import User
from app.schemas.common import ResponseModel, ListResponse
from app.api.deps import get_current_user, require_manager, require_labeler, _is_admin
from app.services import task_service, project_service

router = APIRouter()


@router.get("/my-tasks")
def my_tasks(
    status: Optional[str] = Query(None),
    db: Session = Depends(get_db),
    current_user: User = Depends(require_labeler),
):
    # Data isolation: non-admin users only see tasks assigned to them
    assignee_id = None if _is_admin(current_user) else current_user.id
    items, _ = task_service.list_tasks(db, assignee_id=assignee_id, status=status)
    data = []
    for t in items:
        project = project_service.get_project(db, t.project_id)
        data.append({
            "id": t.id,
            "name": t.name or (project.name if project else f"任务#{t.id}"),
            "project_id": t.project_id,
            "project_name": project.name if project else None,
            "status": t.status,
            "deadline": t.deadline.isoformat() if t.deadline else None,
            "created_at": t.created_at.isoformat() if t.created_at else None,
        })
    return ResponseModel(data=data)


@router.post("/my-tasks/{task_id}/start")
def start_task(
    task_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    task = task_service.get_task(db, task_id)
    if not task:
        from fastapi import HTTPException, status
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="任务不存在")
    task = task_service.update_task_status(db, task, "in_progress")
    return ResponseModel(data={"id": task.id, "status": task.status})


@router.post("/my-tasks/{task_id}/complete")
def complete_task(
    task_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    task = task_service.get_task(db, task_id)
    if not task:
        from fastapi import HTTPException, status
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="任务不存在")
    task = task_service.update_task_status(db, task, "completed")
    return ResponseModel(data={"id": task.id, "status": task.status})


@router.get("/my-tasks/{task_id}/items")
def task_items(
    task_id: int,
    keyword: Optional[str] = Query(None),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    task = task_service.get_task(db, task_id)
    if not task:
        from fastapi import HTTPException, status
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="任务不存在")
    items = task_service.get_task_label_items(db, task.project_id, keyword=keyword)
    return ResponseModel(data=items)


@router.post("/results/{result_id}/label")
def label_result(
    result_id: int,
    category_id: int,
    level_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    result = project_service.update_result_label(db, result_id, category_id, level_id, current_user.id)
    return ResponseModel(data={
        "result_id": result.id,
        "category_id": result.category_id,
        "level_id": result.level_id,
        "status": result.status,
    })


@router.post("/projects/{project_id}/create-task")
def create_task_for_project(
    project_id: int,
    name: str,
    assignee_id: int,
    target_type: str = Query("column"),
    db: Session = Depends(get_db),
    current_user: User = Depends(require_manager),
):
    task = task_service.create_task(
        db, project_id=project_id, name=name,
        assigner_id=current_user.id, assignee_id=assignee_id,
        target_type=target_type,
    )
    return ResponseModel(data={"id": task.id, "name": task.name})
