__all__ = ['parse_arguments']

import json
import sys

from .json_stream import *

def parse_arguments(arguments):
    args = []
    kwargs = {}
    options = {}
    kw = True
    for a in arguments:
        if a == '--':
            kw = False
        elif a.startswith('--') and kw:
            if '=' in a:
                key, value = a[2:].split('=', 1)
                kwargs[key.replace('-', '_')] = parse_value(value)
            else:
                kwargs[a[2:].replace('-', '_')] = True
        elif a.startswith('^'):
            if '=' in a:
                key, value = a[1:].split('=', 1)
                options[key.replace('-', '_')] = parse_value(value)
            else:
                options[a[1:].replace('-', '_')] = True
        elif a == '-':
            args.append(sys.stdin.buffer)
        elif a == '=':
            args.append(json_stream(echo=options.get('echo', False)))
        else:
            args.append(parse_value(a))
    return args, kwargs, options

def parse_value(a):
    try:
        if a.startswith('0x'):
            return int(a, 16)
        else:
            return json.loads(a)
    except Exception:
        return a
