from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
import uuid
from datetime import datetime

from ..db import get_db
from ..models import Workflow
from ..schemas import WorkflowCreate, WorkflowUpdate, WorkflowOut

router = APIRouter(prefix="/workflows", tags=["Workflows"])


@router.get("")
def list_workflows(
    page: int = 1,
    limit: int = 50,
    db: Session = Depends(get_db)
):
    """获取工作流列表"""
    query = db.query(Workflow)
    total = query.count()
    workflows = query.order_by(Workflow.created_at.desc()) \
        .offset((page - 1) * limit).limit(limit).all()
    return {"total": total, "page": page, "limit": limit, "list": workflows}


@router.post("", response_model=WorkflowOut)
def create_workflow(data: WorkflowCreate, db: Session = Depends(get_db)):
    """创建工作流"""
    workflow = Workflow(
        id=str(uuid.uuid4())[:8],
        user_id=1,
        name=data.name,
        node_count=data.nodeCount,
        created_at=data.createdAt or datetime.utcnow().isoformat(),
        updated_at=data.updatedAt or "",
        global_prompt=data.globalPrompt,
        nodes=data.nodes,
        edges=data.edges,
    )
    db.add(workflow)
    db.commit()
    db.refresh(workflow)
    return workflow


@router.get("/{id}", response_model=WorkflowOut)
def get_workflow(id: str, db: Session = Depends(get_db)):
    """获取单个工作流"""
    workflow = db.query(Workflow).filter(Workflow.id == id).first()
    if not workflow:
        raise HTTPException(status_code=404, detail="Workflow not found")
    return workflow


@router.put("/{id}", response_model=WorkflowOut)
def update_workflow(id: str, data: WorkflowUpdate, db: Session = Depends(get_db)):
    """更新工作流"""
    workflow = db.query(Workflow).filter(Workflow.id == id).first()
    if not workflow:
        raise HTTPException(status_code=404, detail="Workflow not found")

    update_data = data.model_dump(exclude_unset=True)
    field_map = {
        "nodeCount": "node_count",
        "globalPrompt": "global_prompt",
    }
    for field, value in update_data.items():
        setattr(workflow, field_map.get(field, field), value)

    workflow.updated_at = datetime.utcnow().isoformat()
    db.commit()
    db.refresh(workflow)
    return workflow


@router.delete("/{id}")
def delete_workflow(id: str, db: Session = Depends(get_db)):
    """删除工作流"""
    workflow = db.query(Workflow).filter(Workflow.id == id).first()
    if not workflow:
        raise HTTPException(status_code=404, detail="Workflow not found")
    db.delete(workflow)
    db.commit()
    return {"message": "Deleted successfully"}
