from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from starlette.responses import JSONResponse
import subprocess

app = FastAPI()

# Add CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.post("/start")
def start_vpn():
    try:
        subprocess.run(["openvpn", "--config", "/path/to/config.conf"], check=True)
        return JSONResponse(content={"status": "started"}, status_code=200)
    except:
        return JSONResponse(content={"error": "Failed to start VPN"}, status_code=500)

@app.post("/stop")
def stop_vpn():
    try:
        subprocess.run(["pkill", "openvpn"], check=True)
        return JSONResponse(content={"status": "stopped"}, status_code=200)
    except:
        return JSONResponse(content={"error": "Failed to stop VPN"}, status_code=500)

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=5000)