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.services import project_service
from app.api.deps import get_current_user

router = APIRouter()


@router.get("")
def list_projects(
    page: int = Query(1, ge=1),
    page_size: int = Query(20, ge=1, le=500),
    keyword: Optional[str] = Query(None),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    items, total = project_service.list_projects(db, keyword=keyword, page=page, page_size=page_size)
    data = []
    for p in items:
        stats = project_service.get_project_stats(db, p.id)
        data.append({
            "id": p.id,
            "name": p.name,
            "template_id": p.template_id,
            "status": p.status,
            "planned_start": p.planned_start.isoformat() if p.planned_start else None,
            "planned_end": p.planned_end.isoformat() if p.planned_end else None,
            "created_at": p.created_at.isoformat() if p.created_at else None,
            "stats": stats,
        })
    return ListResponse(data=data, total=total, page=page, page_size=page_size)


@router.post("")
def create_project(
    name: str,
    template_id: int,
    target_source_ids: Optional[str] = None,
    description: Optional[str] = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    item = project_service.create_project(
        db, name=name, template_id=template_id,
        created_by=current_user.id,
        target_source_ids=target_source_ids,
        description=description,
    )
    return ResponseModel(data={"id": item.id, "name": item.name})


@router.get("/{project_id}")
def get_project(
    project_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    p = project_service.get_project(db, project_id)
    if not p:
        from fastapi import HTTPException, status
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="项目不存在")
    stats = project_service.get_project_stats(db, p.id)
    return ResponseModel(data={
        "id": p.id,
        "name": p.name,
        "template_id": p.template_id,
        "status": p.status,
        "description": p.description,
        "target_source_ids": p.target_source_ids,
        "planned_start": p.planned_start.isoformat() if p.planned_start else None,
        "planned_end": p.planned_end.isoformat() if p.planned_end else None,
        "created_at": p.created_at.isoformat() if p.created_at else None,
        "stats": stats,
    })


@router.delete("/{project_id}")
def delete_project(
    project_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    project_service.delete_project(db, project_id)
    return ResponseModel(message="删除成功")


@router.post("/{project_id}/auto-classify")
def project_auto_classify(
    project_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    from app.services.classification_engine import run_auto_classification
    result = run_auto_classification(db, project_id)
    return ResponseModel(data=result)
