Newer
Older
cortex-hub / ai-hub / app / api / routes / skills.py
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from app.db import models
from app.api import schemas
from app.api.dependencies import ServiceContainer, get_current_user, get_db

def create_skills_router(services: ServiceContainer) -> APIRouter:
    router = APIRouter(prefix="/skills", tags=["Skills"])

    @router.get("/", response_model=List[schemas.SkillResponse])
    def list_skills(
        db: Session = Depends(get_db),
        current_user: models.User = Depends(get_current_user)
    ):
        """List all skills accessible to the user (their own, group skills, and system skills)."""
        system_skills = db.query(models.Skill).filter(models.Skill.is_system == True).all()
        user_skills = db.query(models.Skill).filter(
            models.Skill.owner_id == current_user.id,
            models.Skill.is_system == False
        ).all()
        group_skills = []
        if current_user.group_id:
            group_skills = db.query(models.Skill).filter(
                models.Skill.group_id == current_user.group_id,
                models.Skill.owner_id != current_user.id,
                models.Skill.is_system == False
            ).all()
        return system_skills + user_skills + group_skills

    @router.post("/", response_model=schemas.SkillResponse)
    def create_skill(
        skill: schemas.SkillCreate,
        db: Session = Depends(get_db),
        current_user: models.User = Depends(get_current_user)
    ):
        """Create a new skill."""
        existing = db.query(models.Skill).filter(models.Skill.name == skill.name).first()
        if existing:
            raise HTTPException(status_code=400, detail="Skill with this name already exists")
            
        db_skill = models.Skill(
            name=skill.name,
            description=skill.description,
            skill_type=skill.skill_type,
            config=skill.config,
            owner_id=current_user.id,
            group_id=skill.group_id,
            is_system=skill.is_system if current_user.role == 'admin' else False
        )
        db.add(db_skill)
        db.commit()
        db.refresh(db_skill)
        return db_skill

    @router.put("/{skill_id}", response_model=schemas.SkillResponse)
    def update_skill(
        skill_id: int,
        skill_update: schemas.SkillUpdate,
        db: Session = Depends(get_db),
        current_user: models.User = Depends(get_current_user)
    ):
        """Update an existing skill. User must be admin or the owner."""
        db_skill = db.query(models.Skill).filter(models.Skill.id == skill_id).first()
        if not db_skill:
            raise HTTPException(status_code=404, detail="Skill not found")
            
        if db_skill.owner_id != current_user.id and current_user.role != 'admin':
            raise HTTPException(status_code=403, detail="Not authorized to update this skill")
            
        if skill_update.name is not None and skill_update.name != db_skill.name:
            existing = db.query(models.Skill).filter(models.Skill.name == skill_update.name).first()
            if existing:
                raise HTTPException(status_code=400, detail="Skill with this name already exists")
                
        for key, value in skill_update.model_dump(exclude_unset=True).items():
            if key == 'is_system' and current_user.role != 'admin':
                continue
            setattr(db_skill, key, value)
            
        db.commit()
        db.refresh(db_skill)
        return db_skill

    @router.delete("/{skill_id}")
    def delete_skill(
        skill_id: int,
        db: Session = Depends(get_db),
        current_user: models.User = Depends(get_current_user)
    ):
        """Delete a skill."""
        db_skill = db.query(models.Skill).filter(models.Skill.id == skill_id).first()
        if not db_skill:
            raise HTTPException(status_code=404, detail="Skill not found")
            
        if db_skill.owner_id != current_user.id and current_user.role != 'admin':
            raise HTTPException(status_code=403, detail="Not authorized to delete this skill")
            
        db.delete(db_skill)
        db.commit()
        return {"message": "Skill deleted"}

    return router