from fastapi import APIRouter, HTTPException, Body, Path from typing import List, Dict, Any import json from app.services.config_service import ConfigService from app.schemas.config import ConfigCreate, ConfigUpdate, ConfigResponse router = APIRouter() config_service = ConfigService() @router.get("/", response_model=List[ConfigResponse]) async def list_configs(): """List all available configurations.""" return config_service.list_configs() @router.get("/{name}", response_model=ConfigResponse) async def get_config(name: str = Path(..., description="Configuration name")): """Get a specific configuration by name.""" return config_service.get_config(name) @router.post("/", response_model=ConfigResponse, status_code=201) async def create_config(config_data: ConfigCreate): """Create a new configuration.""" return config_service.create_config(config_data.name, config_data.dict(exclude={"name"})) @router.put("/{name}", response_model=ConfigResponse) async def update_config(name: str, config_data: ConfigUpdate): """Update an existing configuration.""" return config_service.update_config(name, config_data.dict(exclude_unset=True)) @router.delete("/{name}", response_model=Dict[str, Any]) async def delete_config(name: str = Path(..., description="Configuration name")): """Delete a configuration.""" return config_service.delete_config(name) @router.get("/repository/{repository}") async def get_config_by_repository(repository: str): """Find configuration by repository.""" configs = config_service.list_configs() for config in configs: if config.get("repository") == repository: return config raise HTTPException(status_code=404, detail=f"No configuration found for repository: {repository}") @router.get("/job/{job_id}") async def get_config_by_job(job_id: str): """Find configuration by job ID.""" configs = config_service.list_configs() for config in configs: if config.get("job_id") == job_id: return config raise HTTPException(status_code=404, detail=f"No configuration found for job_id: {job_id}") @router.post("/link") async def link_repository_to_job( repository: str = Body(..., embed=True), job_id: str = Body(..., embed=True), name: str = Body(None, embed=True) ): """Link a repository to a job.""" # Generate a name if not provided if not name: name = f"{job_id.lower().replace('/', '_').replace(' ', '_')}" # Create the config config = { "repository": repository, "job_id": job_id, } return config_service.create_config(name, config) @router.post("/unlink/{name}") async def unlink_repository_from_job(name: str): """Unlink a repository from a job by deleting the configuration.""" return config_service.delete_config(name)