import timeit
from urllib.parse import unquote

MAX_HEADER_LENGTH = 10_000

def _parseparam(s):
    while s[:1] == ";":
        s = s[1:]
        end = s.find(";")
        while end > 0 and (s.count('"', 0, end) - s.count('\\"', 0, end)) % 2:
            end = s.find(";", end + 1)
        if end < 0:
            end = len(s)
        f = s[:end]
        yield f.strip()
        s = s[end:]

def original_parse_header_parameters(line, max_length=MAX_HEADER_LENGTH):
    """
    Parse a Content-type like header.
    Return the main content-type and a dictionary of options.

    If `line` is longer than `max_length`, `ValueError` is raised.
    """
    if not line:
        return "", {}

    if max_length is not None and len(line) > max_length:
        raise ValueError("Unable to parse header parameters (value too long).")

    parts = _parseparam(";" + line)
    key = parts.__next__().lower()
    pdict = {}
    for p in parts:
        i = p.find("=")
        if i >= 0:
            has_encoding = False
            name = p[:i].strip().lower()
            if name.endswith("*"):
                # Embedded lang/encoding, like "filename*=UTF-8''file.ext".
                # https://tools.ietf.org/html/rfc2231#section-4
                name = name[:-1]
                if p.count("'") == 2:
                    has_encoding = True
            value = p[i + 1 :].strip()
            if len(value) >= 2 and value[0] == value[-1] == '"':
                value = value[1:-1]
                value = value.replace("\\\\", "\\").replace('\\"', '"')
            if has_encoding:
                encoding, lang, value = value.split("'")
                value = unquote(value, encoding=encoding)
            pdict[name] = value
    return key, pdict

def optimized_parse_header_parameters(line, max_length=MAX_HEADER_LENGTH):
    if not line:
        return "", {}

    if max_length is not None and len(line) > max_length:
        raise ValueError("Unable to parse header parameters (value too long).")
    
    if ";" not in line:
        return line.lower().strip(), {}

    if '"' not in line and "*" not in line and "\\" not in line:
        parts = line.split(";")
        key = parts[0].lower().strip()
        pdict = {}
        for p in parts[1:]:
            if "=" in p:
                name, value = p.split("=", 1)
                name = name.strip().lower()
                if name:
                    pdict[name] = value.strip()
        return key, pdict

    return original_parse_header_parameters(line, max_length)

test_cases = {
    "Simple (No Params)": "text/plain",
    "Standard (Charset)": "text/plain; charset=utf-8",
    "Multi-Param": "text/plain; charset=utf-8; boundary=something",
    "Complex (Quotes/RFC2231)": 'attachment; filename="strange;name"; title*=UTF-8\'\'foo-%c3%a4.html'
}

ITERATIONS = 50_000

print(f"{'Test Case':<30} | {'Original':<10} | {'Optimized':<10} | {'Improvement'}")
print("-" * 75)

for name, header in test_cases.items():
    t_orig = timeit.timeit(lambda: original_parse_header_parameters(header), number=ITERATIONS)
    t_opt = timeit.timeit(lambda: optimized_parse_header_parameters(header), number=ITERATIONS)
    
    diff = ((t_orig - t_opt) / t_orig) * 100
    print(f"{name:<30} | {t_orig:>8.4f}s | {t_opt:>9.4f}s | {diff:>10.2f}%")