from fastapi import FastAPI, HTTPException
import subprocess
import os
from pydantic import BaseModel

app = FastAPI()

class CommandRequest(BaseModel):
    command: str
    working_dir: str

@app.post("/execute")
async def execute_command(cmd: CommandRequest):
    try:
        # Validate working directory exists
        if not os.path.isdir(cmd.working_dir):
            raise HTTPException(status_code=400, detail="Working directory does not exist")

        # Execute the command in the specified directory
        result = subprocess.run(
            cmd.command,
            cwd=cmd.working_dir,
            shell=True,
            capture_output=True,
            text=True
        )

        if result.returncode != 0:
            return {
                "status": "failed",
                "returncode": result.returncode,
                "stderr": result.stderr
            }
        
        return {
            "status": "success",
            "returncode": result.returncode,
            "stdout": result.stdout
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))