"""
Project illustrative log records without network access or executing supplied code.
Run with Python 3.10+; self-checks run before the JSON demonstration.
"""

import hashlib
import json
from typing import Any

# Each tuple is one illustrative request completion, not a measured incident.
FIXTURE = (
    ("checkout", "INFO", "r1", 1800, "payment retry succeeded"),
    ("checkout", "INFO", "r2", 2100, "payment retry succeeded"),
    ("checkout", "INFO", "r3", 2200, "payment upstream timed out; retry succeeded"),
    ("checkout", "ERROR", "r4", 25, "invalid order rejected"),
    ("checkout", "INFO", "r5", 1900, "payment retry succeeded"),
    ("checkout", "INFO", "r6", 2400, "payment retry succeeded"),
    ("checkout", "INFO", "r7", 50, "completed without retry"),
    ("search", "INFO", "r8", 1700, "search index retry succeeded"),
)
RAW = b"\n".join(
    json.dumps(
        dict(
            service=service,
            level=level,
            request=request,
            latency_ms=latency,
            message=message,
            debug="illustrative stack frame; " * 24,
        ),
        separators=(",", ":"),
    ).encode("utf-8")
    for service, level, request, latency, message in FIXTURE
)
SOURCE = "sha256:" + hashlib.sha256(RAW).hexdigest()
MAX_VIEW_BYTES = 2048


def encode_view(view: dict[str, Any]) -> bytes:
    """
    Reject an oversized view before exposing it; never cut serialized JSON mid-record.
    """
    payload = json.dumps(view, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
    if len(payload) > MAX_VIEW_BYTES:
        raise ValueError("view exceeds byte budget")
    return payload


def project(level: str | None = None, limit: int = 2) -> dict[str, Any]:
    """
    Count checkout completions and retain bounded examples of requests taking at least 1000 ms.
    The fixed RAW fixture stands in for an already authorized, immutable artifact.
    """
    if level not in (None, "INFO", "ERROR") or not 0 <= limit <= 3:
        raise ValueError("unsupported level or sample limit")

    matched = slow = 0
    samples: list[dict[str, Any]] = []
    for line, raw_record in enumerate(RAW.splitlines(), 1):
        record = json.loads(raw_record)
        if record["service"] != "checkout" or (level is not None and record["level"] != level):
            continue
        matched += 1
        if record["latency_ms"] >= 1000:
            slow += 1
            if len(samples) < limit:
                sample = {key: record[key] for key in ("request", "latency_ms", "message")}
                sample["message"] = record["message"][:96]
                sample["message_truncated"] = len(record["message"]) > 96
                samples.append({"line": line, **sample})

    view = {
        "source": SOURCE,
        "query": {"service": "checkout", "level": level, "slow_ms": 1000, "sample_limit": limit},
        "matched": matched,
        "slow": slow,
        "samples": samples,
        "omitted_slow": slow - len(samples),
    }
    encode_view(view)
    return view


def recover(source: str, line: int) -> dict[str, Any]:
    """
    Resolve an artifact hash and one-based line to an original record, with a bounded response.
    """
    if source != SOURCE:
        raise ValueError("unknown artifact")
    records = RAW.splitlines()
    if not 1 <= line <= len(records):
        raise ValueError("line outside artifact")
    view = {"source": source, "line": line, "record": json.loads(records[line - 1])}
    encode_view(view)
    return view


def self_check() -> None:
    """
    Check scope, filter bias, sample omission, exact recovery, and serialized output limits.
    """
    wrong = project("ERROR")
    assert (wrong["matched"], wrong["slow"]) == (1, 0)
    correct = project()
    assert (correct["matched"], correct["slow"], correct["omitted_slow"]) == (7, 5, 3)
    assert [row["line"] for row in correct["samples"]] == [1, 2]
    assert project(limit=0)["omitted_slow"] == 5
    assert project(limit=3)["omitted_slow"] == 2
    assert recover(SOURCE, 3)["record"] == json.loads(RAW.splitlines()[2])
    assert hashlib.sha256(RAW).hexdigest() == SOURCE.removeprefix("sha256:")
    for invalid_view in ({"text": "x" * MAX_VIEW_BYTES}, {"text": "\u00e9" * (MAX_VIEW_BYTES // 2)}):
        try:
            encode_view(invalid_view)
        except ValueError:
            pass
        else:
            raise AssertionError("oversized view accepted")
    for invalid_limit in (-1, 4):
        try:
            project(limit=invalid_limit)
        except ValueError:
            pass
        else:
            raise AssertionError("invalid sample limit accepted")


if __name__ == "__main__":
    self_check()
    correct_view = project()
    expanded_view = project(limit=3)
    request_ref = expanded_view["samples"][2]
    print(
        json.dumps(
            {
                "self_check": "passed",
                "raw_rows": len(RAW.splitlines()),
                "raw_bytes": len(RAW),
                "projected_bytes": len(encode_view(correct_view)),
                "max_view_bytes": MAX_VIEW_BYTES,
                "wrong_filter": project("ERROR"),
                "model_view": correct_view,
                "follow_up": recover(SOURCE, request_ref["line"]),
            },
            indent=2,
        )
    )
