import shlex
import urllib.parse
import json


def parse_curl(curl_command: str) -> dict:
    tokens = shlex.split(curl_command)

    method = "GET"
    explicit_method = False
    url = ""
    headers = {}
    body = None

    i = 0
    while i < len(tokens):
        token = tokens[i]

        if token in ("-X", "--request") and i + 1 < len(tokens):
            method = tokens[i + 1].upper()
            explicit_method = True
            i += 2
            continue

        if token.startswith("http"):
            url = token
            i += 1
            continue

        if token in ("--url",) and i + 1 < len(tokens):
            url = tokens[i + 1]
            i += 2
            continue

        if token in ("-H", "--header") and i + 1 < len(tokens):
            header = tokens[i + 1]
            key, value = header.split(":", 1)
            headers[key.strip().lower()] = value.strip()
            i += 2
            continue

        if token in ("-d", "--data", "--data-raw") and i + 1 < len(tokens):
            body = tokens[i + 1]
            if not explicit_method and method == "GET":
                method = "POST"
            i += 2
            continue

        i += 1

    # -------------------- URL PARSING (CRITICAL) --------------------
    parsed_url = urllib.parse.urlparse(url)

    params = dict(urllib.parse.parse_qsl(parsed_url.query))

    clean_url = urllib.parse.urlunparse(
        parsed_url._replace(query="")
    )

    parsed_body = {}
    if body:
        try:
            parsed_body = json.loads(body)
        except Exception:
            parsed_body = body

    return {
        "method": method,
        "url": clean_url,
        "headers": headers,
        "params": params,      # 🔥 THIS UNBLOCKS ALL TESTS
        "body": parsed_body or {},
    }
