import json
import os
from pathlib import Path
import subprocess
import sys
import signal
import pytest
import requests

import ray
from ray import serve
from ray.tests.conftest import tmp_working_dir  # noqa: F401, E501
from ray._private.test_utils import wait_for_condition
from ray.dashboard.optional_utils import RAY_INTERNAL_DASHBOARD_NAMESPACE
from ray.serve.scripts import process_args_and_kwargs


def ping_endpoint(endpoint: str, params: str = ""):
    try:
        return requests.get(f"http://localhost:8000/{endpoint}{params}").text
    except requests.exceptions.ConnectionError:
        return "connection error"


@pytest.fixture
def ray_start_stop():
    subprocess.check_output(["ray", "start", "--head"])
    yield
    subprocess.check_output(["ray", "stop", "--force"])


class TestProcessArgsAndKwargs:
    def test_valid_args_and_kwargs(self):
        args_and_kwargs = (
            "argval1",
            "argval2",
            "--kwarg1",
            "kwval1",
            "--kwarg2",
            "kwval2",
        )
        args, kwargs = process_args_and_kwargs(args_and_kwargs)
        assert args == ["argval1", "argval2"]
        assert kwargs == {"kwarg1": "kwval1", "kwarg2": "kwval2"}

    def test_mixed_args_and_kwargs(self):
        args_and_kwargs = (
            "argval1",
            "--kwarg1",
            "kwval1",
            "argval2",
            "--kwarg2",
            "kwval2",
        )
        with pytest.raises(ValueError):
            process_args_and_kwargs(args_and_kwargs)

    def test_mixed_kwargs(self):
        args_and_kwargs = (
            "argval1",
            "argval2",
            "--kwarg1==kw==val1",
            "--kwarg2",
            "kwval2",
            "--kwarg3",
            "=kwval=3",
            "--kwarg4=",