# Chapter 14 — destructuring JSON request log records.
#
# Each line of event.jsonl is one HTTP request, modelled as a
# self-describing JSON object. The single-json-column extensional
# consumes the line as-is; rules pull fields out via subscript
# and coerce leaves to primitive SQL types so we can compare them
# with regular literals.

extensional event(payload: value).

# Coerce the top-level scalar fields to primitive SQL types.
request(Id, Method, Path, Status) :-
    event(E),
    Id = as_integer(E["id"]),
    Method = as_string(E["method"]),
    Path = as_string(E["path"]),
    Status = as_integer(E["status"]).

# Now we can compare against regular literals — Method is `string`,
# Status is `integer`. The slice `Path[0:4]` works on a string just
# like any string operation from Chapter 6.
ok_v1_request(Id, Path) :-
    request(Id, _, Path, Status),
    Status >= 200,
    Status < 300,
    Path[0:4] = "/v1/".

# Iterate the headers object — one row per (event-id, key) pair.
event_string_header(Id, Key, Value) :-
    event(E),
    Id = as_integer(E["id"]),
    object_entry(E["headers"], Key, V),
    Value = as_string(V).

?- request(Id, M, P, S).
?- ok_v1_request(Id, P).
?- event_string_header(Id, K, V).
