import os
import requests
from dotenv import load_dotenv

load_dotenv()

BASE_URL = "https://beta-api.runcomfy.net/prod/api"
USER_ID = os.getenv("RUNCOMFY_USER_ID")
API_TOKEN = os.getenv("API_TOKEN")

def stop_server(server_id: str) -> dict:
    """Stop RunComfy server instance"""
    if not USER_ID or not API_TOKEN:
        return {
            "server_id": server_id,
            "status": "Error",
            "message": "Missing RUNCOMFY_USER_ID or API_TOKEN environment variables"
        }
    
    headers = {"Authorization": f"Bearer {API_TOKEN}"}
    url = f"{BASE_URL}/users/{USER_ID}/servers/{server_id}"
    
    try:
        resp = requests.delete(url, headers=headers, timeout=30)
        
        if resp.status_code == 200:
            return {
                "server_id": server_id,
                "status": "Deleted",
                "message": f"Server {server_id} successfully stopped"
            }
        elif resp.status_code == 404:
            return {
                "server_id": server_id,
                "status": "NotFound",
                "message": f"Server {server_id} not found or already deleted"
            }
        else:
            return {
                "server_id": server_id,
                "status": "Error",
                "message": f"HTTP {resp.status_code}: {resp.text}"
            }
    except Exception as e:
        return {
            "server_id": server_id,
            "status": "Error",
            "message": f"Request failed: {str(e)}"
        }
