"""Measure one UTF-8 Markdown byte snapshot with explicit line definitions.

Research measurement only: no agent dispatch, filesystem sandbox, or semantic
Markdown parsing. LF and CRLF line endings are accepted; bare CR is rejected.
"""

import argparse
import hashlib
import json
from pathlib import Path


def measure_bytes(data):
    text = data.decode("utf-8-sig")
    if "\r" in text.replace("\r\n", ""):
        raise ValueError("Bare CR line endings are outside this measurement definition")
    normalized = text.replace("\r\n", "\n")
    lines = normalized.split("\n") if normalized else []
    if normalized.endswith("\n"):
        lines.pop()
    headings = [{"line": number, "text": line} for number, line in enumerate(lines, 1) if line.startswith("## ")]
    return {
        "measurement_version": "1.0",
        "sha256": hashlib.sha256(data).hexdigest(),
        "bytes": len(data),
        "encoding": "UTF-8; optional BOM excluded from text metrics but retained in byte hash",
        "line_definition": "LF/CRLF delimited segments; empty lines included; terminal delimiter does not add a line",
        "newline_count": data.count(b"\n"),
        "logical_line_count": len(lines),
        "nonempty_line_count": sum(line != "" for line in lines),
        "nonblank_line_count": sum(bool(line.strip()) for line in lines),
        "lexical_h2_count": len(headings),
        "lexical_h2_headings": headings,
    }


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("file", type=Path)
    args = parser.parse_args()
    path = args.file.resolve(strict=True)
    receipt = measure_bytes(path.read_bytes())
    receipt["actual_path"] = str(path)
    print(json.dumps(receipt, indent=2, ensure_ascii=True))
