#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""EP03 S7-2 交付 8800 下载自测：/list 在列、CL 一致、下载字节逐字节、zip CRC"""
import hashlib, json, os, urllib.request, zipfile

HERE = os.path.dirname(os.path.abspath(__file__))
P = os.path.join(HERE, "ep03_s72_monk_2cands.zip")
NAME = os.path.basename(P)
OP = urllib.request.build_opener(urllib.request.ProxyHandler({}))
BASE = "http://localhost:8800"


def sha(b):
    return hashlib.sha256(b).hexdigest()


def main():
    local = open(P, "rb").read()
    lsha = sha(local)
    print("LOCAL", len(local), lsha)
    # /list
    lst = json.loads(OP.open(BASE + "/list", timeout=10).read().decode())
    print("LIST_CONTAINS", NAME in lst, "list_n", len(lst))
    # /download
    r = OP.open(BASE + "/download?name=" + urllib.parse.quote(NAME), timeout=30)
    cl = r.headers.get("Content-Length")
    data = r.read()
    print("HTTP", r.status, "CL", cl, "GOT", len(data))
    print("CL_MATCH", int(cl) == len(local))
    print("BYTES_IDENTICAL", data == local, "sha", sha(data))
    # zip CRC
    with zipfile.ZipFile(P) as z:
        bad = z.testzip()
        print("ZIP_BAD", bad, "members", len(z.infolist()))
        for n in ["ep03_s72_monk_cand1_front.png", "ep03_s72_monk_cand2_front.png"]:
            b = z.read(n)
            from PIL import Image
            import io
            im = Image.open(io.BytesIO(b))
            print("  ", n, len(b), sha(b), im.size, im.mode)
    ok = (NAME in lst and int(cl) == len(local) and data == local and bad is None)
    print("SELFTEST", "PASS" if ok else "FAIL")


if __name__ == "__main__":
    import urllib.parse
    main()
