#!/usr/bin/env python3
"""Offline checks for normalized metadata from one ordinary successful GET.

Transfer framing is assumed already handled by the client stack. The synthetic
headers/body are not raw HTTP, a wire capture, a provider meter, an HTTP parser,
or a production content-decoder.
"""
import gzip
import zlib


PAYLOAD = ('{"item":"café","note":"\u4ee3\u7406\u54cd\u5e94\u538b\u7f29\u9a8c\u6536",'
           '"enabled":true,"tags":["alpha","beta","alpha","beta","alpha","beta"]}')
IDENTITY = PAYLOAD.encode("utf-8")
GZIP = gzip.compress(IDENTITY, compresslevel=9, mtime=0)


class Hold(Exception):
    """Expected refusal: no decoded body may be accepted."""


def accept(headers, coded_body):
    """Accept identity or gzip once, with a deliberately narrow header contract."""
    encoding = headers.get("Content-Encoding", "identity").lower()
    declared = headers.get("Content-Length")
    if declared is not None:
        try:
            if int(declared) != len(coded_body):
                raise Hold("declared Content-Length differs from coded bytes")
        except ValueError as exc:
            raise Hold("Content-Length is not an integer") from exc
    if encoding == "identity":
        decoded = coded_body
    elif encoding == "gzip":
        try:
            decoded = gzip.decompress(coded_body)
        except (gzip.BadGzipFile, OSError, EOFError, zlib.error) as exc:
            raise Hold("gzip body cannot be completely decoded") from exc
    else:
        raise Hold("unsupported Content-Encoding: " + encoding)
    if decoded != IDENTITY:
        raise Hold("decoded bytes do not match the expected representation")
    return decoded


def show(label, headers, body):
    decoded = accept(headers, body)
    print(f"{label}: coded_bytes={len(body)} decoded_bytes={len(decoded)} "
          f"characters={len(decoded.decode('utf-8'))} "
          f"declared_content_length={headers.get('Content-Length', 'absent')} "
          f"decoded_body_equal={decoded == IDENTITY}")


def expect_hold(label, headers, body):
    try:
        accept(headers, body)
    except Hold as exc:
        print(f"{label}: HOLD ({exc})")
        return
    raise AssertionError(label + " was accepted")


def main():
    show("identity", {"Content-Length": str(len(IDENTITY))}, IDENTITY)
    show("gzip", {"Content-Encoding": "gzip", "Content-Length": str(len(GZIP))}, GZIP)
    show("identity_no_content_length", {}, IDENTITY)
    expect_hold("mismatched_declared_length", {"Content-Encoding": "gzip", "Content-Length": str(len(GZIP) + 1)}, GZIP)
    expect_hold("truncated_gzip", {"Content-Encoding": "gzip", "Content-Length": str(len(GZIP) - 4)}, GZIP[:-4])
    expect_hold("unsupported_encoding", {"Content-Encoding": "br", "Content-Length": str(len(GZIP))}, GZIP)
    assert gzip.decompress(GZIP) == IDENTITY
    print("checks_completed=6 accepted=3 held=3")


if __name__ == "__main__":
    main()
