import argparse,json,re
from urllib.request import Request,urlopen
from urllib.error import HTTPError
from urllib.parse import urlsplit

def parse_range(text):
    match=re.fullmatch(r"bytes (\d+)-(\d+)/(\d+|\*)",text or "")
    if not match:return None
    start,end=int(match[1]),int(match[2]);total=None if match[3]=="*" else int(match[3])
    if end<start or (total is not None and end>=total):return None
    return {"start":start,"end":end,"total":total}

def check(url):
    if urlsplit(url).scheme not in ("http","https"):
        raise ValueError("HTTP(S) URL required")
    request=Request(url,headers={"Range":"bytes=0-1023","Accept-Encoding":"identity"})
    try:response=urlopen(request,timeout=15)
    except HTTPError as error:response=error
    with response:
        status=response.status
        headers={key:response.headers.get(key) for key in ("Content-Type","Content-Length","Content-Range","Accept-Ranges","Content-Encoding")}
        body=response.read(1025)
    parsed=parse_range(headers["Content-Range"])
    valid_partial=(status==206 and parsed is not None and parsed["start"]==0
      and parsed["end"]<=1023 and len(body)==parsed["end"]+1
      and headers["Content-Encoding"] in (None,"identity"))
    return {"status":status,"headers":headers,"body_bytes_read_max_1025":len(body),
      "single_range_response_matches_test":valid_partial,
      "seeking_and_codec_not_tested":True}

if __name__=="__main__":
    parser=argparse.ArgumentParser(description="Read-only bounded range check for an audio URL you are authorized to inspect")
    parser.add_argument("url");args=parser.parse_args();print(json.dumps(check(args.url),indent=2))
