import subprocess
import json

def _run_curl(api_url, api_key, endpoint, data_payload):
    if not api_url or not api_key:
        return {"success": False, "error": "API URL or Key not configured for this location.", "data": ""}
    
    curl_command = [
        "curl", "-k", "--location", "--request", "POST", f"{api_url}{endpoint}",
        "--form", f"data={json.dumps(data_payload)}",
        "--form", f"key={api_key}"
    ]
    try:
        response = subprocess.check_output(curl_command, text=True, stderr=subprocess.PIPE)
        return json.loads(response)
    except subprocess.CalledProcessError as e:
        return {"success": False, "error": e.stderr, "data": ""}
    except json.JSONDecodeError as e:
        return {"success": False, "error": "JSON decode error", "data": ""}

def get_bgp_base_path(vrf_name):
    if vrf_name:
        return ["bgp", "vrf", vrf_name]
    else:
        return ["bgp"]

def run_bgp_route_curl_command(api_url, api_key, vrf_name, ip_version, bgprouteprefix):
    path = get_bgp_base_path(vrf_name) + [ip_version, bgprouteprefix]
    return _run_curl(api_url, api_key, "/show", {"op": "show", "path": path})