import importlib.util
from urllib.parse import quote
spec = importlib.util.spec_from_file_location('download_name', Path(__file__).resolve().parent / 'download-name.py')
helper = importlib.util.module_from_spec(spec)
spec.loader.exec_module(helper)
header = 'attachment; filename="report.md"; filename*=UTF-8\'\'' + quote(data['download_name'])
body = output['report'].encode('utf-8')
class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-Disposition', header)
        self.send_header('Content-Type', 'text/markdown; charset=utf-8')
        self.send_header('Content-Length', str(len(body)))
        self.end_headers()
        self.wfile.write(body)
    def log_message(self, *_):
        pass
server = ThreadingHTTPServer(('127.0.0.1', 0), Handler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
    with urllib.request.urlopen(f'http://127.0.0.1:{server.server_port}/report', timeout=5) as response:
        filename = helper.attachment_name(response.headers['Content-Disposition'])
        downloaded = response.read()
    check('实际HTTP响应优先采用UTF-8中文filename*', filename == '门店日报.md')
    with tempfile.TemporaryDirectory() as directory:
        saved = helper.save_new(directory, filename, downloaded)
        check('保存后的SHA256与真实API报告内容一致', hashlib.sha256(saved.read_bytes()).digest() == hashlib.sha256(body).digest())
        try:
            helper.save_new(directory, filename, b'do not overwrite')
            check('同名文件不被覆盖', False)
        except FileExistsError:
            check('同名文件不被覆盖', saved.read_bytes() == body)
    valid = [('attachment; filename="report.md"', 'report.md'), ("attachment; filename*=UTF-8''a+b.md", 'a+b.md'), ("attachment; filename*=UTF-8''a%20b.md", 'a b.md'), ('attachment; filename="semi;colon.md"', 'semi;colon.md')]
    for value, expected_name in valid:
        check('文件名解析：' + expected_name, helper.attachment_name(value) == expected_name)
    for value in ["attachment; filename*=UTF-8''bad%ZZ.md", 'attachment; filename="a"; filename="b"', "attachment; filename*=UTF-8''..%2Fescape.md", "attachment; filename*=UTF-8''bad%0A.md"]:
        try:
            helper.attachment_name(value)
            check('非法文件名反例被拒绝', False, value)
        except (ValueError, UnicodeDecodeError):
            check('非法文件名反例被拒绝', True, value)
    (folder / 'report.md').write_bytes(body)
    result = {'download_name': filename, 'content_sha256': hashlib.sha256(body).hexdigest(), 'bytes': len(body), 'report': output['report']}
finally:
    server.shutdown()
    server.server_close()
    thread.join(timeout=5)
