"""Check a deployed release using a private manifest-link file; URLs not logged."""
import argparse
import json
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen


def main():
    parser=argparse.ArgumentParser()
    parser.add_argument('--link-file', required=True)
    parser.add_argument('--output', default='deployment-results.json')
    parser.add_argument('--media', action='store_true', help='Also probe at most 64 KiB from the first stream in each case')
    args=parser.parse_args()
    url=next(line for line in Path(args.link_file).read_text().splitlines() if line.startswith('https://') and line.endswith('/manifest.json'))
    base=url[:-len('/manifest.json')]
    report={'version':'1.1.3','checks':[]}
    def get(route):
        with urlopen(Request(base+route,headers={'Accept':'application/json'}),timeout=90) as response:
            return json.load(response)
    def record(row):
        report['checks'].append(row); print(json.dumps(row),flush=True)
    manifest=get('/manifest.json')
    assert manifest['version']=='1.1.3' and len(manifest['catalogs'])==6
    record({'manifest':'PASS','catalogs':6})
    for kind,tail in [('movie','top.json'),('series','top.json'),('movie','year.json'),('series','year.json'),('movie','imdbRating.json'),('series','imdbRating.json'),('movie','top/skip=50.json'),('movie','top/search=Interstellar.json'),('series','top/search=Breaking%20Bad.json'),('movie','top/genre=Sci-Fi.json')]:
        try:
            data=get('/catalog/'+kind+'/'+tail)
            record({'route':'catalog/'+kind+'/'+tail,'count':len(data.get('metas',[]))})
        except HTTPError as error: record({'route':'catalog/'+kind+'/'+tail,'http':error.code})
    for kind,ident,title in [('movie','tt0816692','Interstellar'),('series','tt1475582:1:1','Sherlock S01E01'),('series','tt0903747:2:1','Breaking Bad S02E01')]:
        row={'title':title}
        try:
            meta=get('/meta/'+kind+'/'+ident.split(':')[0]+'.json')['meta']; row['metadata']=meta.get('name'); row['episodeCount']=len(meta.get('videos',[]))
            streams=get('/stream/'+kind+'/'+ident+'.json')['streams']; row['streamCount']=len(streams)
            if args.media and streams:
                headers=dict(streams[0].get('behaviorHints',{}).get('proxyHeaders',{}).get('request',{})); headers['Range']='bytes=0-65535'
                try:
                    with urlopen(Request(streams[0]['url'],headers=headers),timeout=20) as response:
                        data=response.read(65536); row['mediaHTTP']=response.status; row['recognizedMedia']=b'<MPD' in data or b':MPD' in data or data.startswith(b'#EXTM3U') or b'ftyp' in data[:64]
                except HTTPError as error: row['mediaHTTP']=error.code
            row['fullPlaybackVerified']=False
        except HTTPError as error: row['routeHTTP']=error.code
        except (OSError,URLError,ValueError,TypeError): row['error']='Network or response check failed'
        record(row)
    assert get('/stream/series/tt1475582:999:999.json')=={'streams':[]}
    record({'unsupportedEpisode':'No sources returned (PASS)'})
    Path(args.output).write_text(json.dumps(report,indent=2))


if __name__=='__main__': main()
