"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Field, Input, Select, Textarea } from "@/components/ui/field";
import { InspectorFrame, SaidLine, announceManifestChanged, call, refusal, useOnManifestChanged, type InspectorProps, type Said } from "./shared";
// A MEASURE LEDGER's ROWS (umtool redesign L6, item 3; agents added and fixed them with jq this week): the rows the
// instruments draw from, each with its date, scope (a track), form, value (a number, or a regime and its event on
// a regime track), basis (the phrase that settles the scope) and source (src, channel/video, cite) -- added,
// changed or removed through POST /api/report/ledger, the ledger CLI's checks word for word, one undo point each.
// `umtool ledger
add|set|rm` is the twin. With `block` (a timeline entry's id): the rows pinned to it, and a
// new row pinned to it.
type Track = { key: string; label: string; role: string; regimes: string[] | null };
type Schema = {
unit: string; tracks: Track[]; forms: string[]; regimes: { key: string; label: string }[];
fields: { key: string; label: string; kind: string; options: unknown[] | null }[];
events: string[]; promiseForms: string[]; outcomes: string[]; scopeConfidence: string[]; valueKinds: string[];
};
type Row = Record & { id: string };
type View = { kind: "measure" | "headcount" | null; schema: Schema | null; schemaError: string | null; total: number; rows: Row[]; entries: string[]; token: string | null };
/** The keys the form shows, in order: what a row needs, then its source. */
const BASE_KEYS = ["id", "date", "scope", "population", "value", "event", "scopeBasis", "label", "quote", "src", "channel", "video", "cite", "entryId"] as const;
const REQUIRED = new Set(["id", "date", "scope", "population", "scopeBasis"]);
const PAGE = 40;
const textOf = (v: unknown) => (v === undefined || v === null ? "" : Array.isArray(v) ? v.join("|") : String(v));
export default function LedgerInspector({ project, block = null }: InspectorProps) {
const router = useRouter();
const [view, setView] = useState(null);
const [editing, setEditing] = useState(null); // a row id, or "" for a new row
const [form, setForm] = useState>({});
const [filter, setFilter] = useState("");
const [shown, setShown] = useState(PAGE);
const [busy, setBusy] = useState(false);
const [said, setSaid] = useState(null);
const load = useCallback(async () => {
const q = new URLSearchParams({ project, ...(block ? { entry: block } : {}) });
const { ok, j } = await call(`/api/report/ledger?${q.toString()}`);
if (ok) setView(j);
return ok ? j : null;
}, [project, block]);
useEffect(() => {
void load();
}, [load]);
useOnManifestChanged(project, load);
const declared = view?.schema?.fields ?? [];
const keys = useMemo(() => [...BASE_KEYS, ...declared.map((f) => f.key)], [declared]);
const rows = useMemo(() => {
const all = [...(view?.rows ?? [])].sort((a, b) => String(b.date ?? "").localeCompare(String(a.date ?? "")) || a.id.localeCompare(b.id));
const f = filter.trim().toLowerCase();
return f ? all.filter((r) => [r.id, r.date, r.scope, r.population, r.display, r.label, r.quote].some((v) => String(v ?? "").toLowerCase().includes(f))) : all;
}, [view, filter]);
if (!view || !view.kind) return null;
if (view.kind !== "measure" || !view.schema) {
return (
{view.schemaError ?? "This ledger is not a measure ledger (ledgerSchema.kind \"measure\"): its rows are written by its own tools."}
);
}
const s = view.schema;
const track = s.tracks.find((t) => t.key === form.scope) ?? null;
const regimeTrack = track?.role === "regime";
const open = (id: string | null) => {
setSaid(null);
if (id === null) {
setEditing(null);
return;
}
if (id === "") {
const today = new Date().toISOString().slice(0, 10);
setForm({ id: "", date: today, scope: s.tracks[0]?.key ?? "", population: s.forms[0] ?? "", ...(block ? { entryId: block } : {}) });
} else {
const r = view.rows.find((x) => x.id === id);
setForm(Object.fromEntries(keys.map((k) => [k, textOf(r?.[k])])));
}
setEditing(id);
};
const set = (k: string, v: string) => {
setSaid(null);
setForm((f) => ({ ...f, [k]: v }));
};
const save = async () => {
setBusy(true);
setSaid(null);
try {
let body: Record;
if (editing === "") {
const row = Object.fromEntries(Object.entries(form).filter(([, v]) => v.trim() !== "").map(([k, v]) => [k, v.trim()]));
body = { project, token: view.token, op: "add", row };
} else {
const was = view.rows.find((x) => x.id === editing);
const patch: Record = {};
const unset: string[] = [];
for (const k of keys) {
if (k === "id") continue;
const now = (form[k] ?? "").trim();
if (now === textOf(was?.[k])) continue;
if (now === "" && !REQUIRED.has(k)) unset.push(k);
else patch[k] = now;
}
// A new value (or form, or event) is drawn by its own words again: the display is recomputed from it.
if (["value", "population", "event", "scope"].some((k) => k in patch || unset.includes(k))) unset.push("display");
if (!Object.keys(patch).length && !unset.length) {
setSaid({ ok: true, text: "Nothing changed." });
return;
}
body = { project, token: view.token, op: "set", id: editing, patch, unset };
}
const { ok, status, j } = await call<{ row?: Row }>("/api/report/ledger", { method: "POST", body: JSON.stringify(body) });
if (!ok) {
setSaid({ ok: false, text: refusal(j, status) });
if (j.stale) await load();
return;
}
await load();
setEditing(null);
setSaid({ ok: true, text: `${editing === "" ? "Added" : "Saved"} ${j.row?.id ?? ""}: ${String(j.row?.display ?? "")} — in the draft.` });
announceManifestChanged(project);
router.refresh();
} finally {
setBusy(false);
}
};
const remove = async (id: string) => {
setBusy(true);
setSaid(null);
try {
const { ok, status, j } = await call("/api/report/ledger", { method: "POST", body: JSON.stringify({ project, token: view.token, op: "rm", id }) });
if (!ok) {
setSaid({ ok: false, text: refusal(j, status) });
if (j.stale) await load();
return;
}
await load();
setEditing(null);
setSaid({ ok: true, text: `Removed ${id}.` });
announceManifestChanged(project);
router.refresh();
} finally {
setBusy(false);
}
};
const input = (k: string, label: string, hint?: string, extra?: React.ComponentProps<"input">) => (
set(k, e.target.value)} {...extra} />
);
const select = (k: string, label: string, options: { value: string; label: string }[], blank?: string) => (
);
const regimes = regimeTrack ? (track?.regimes ?? s.regimes.map((r) => r.key)) : [];
const editor = editing !== null && (
{editing === "" ? input("id", "Id", "a letter, then letters, digits . : - _") : {editing}}
{input("date", "Date", "YYYY-MM-DD")}
{select("scope", "Scope", s.tracks.map((t) => ({ value: t.key, label: `${t.label} (${t.key})` })))}
{select("population", "Form", s.forms.map((f) => ({ value: f, label: f })))}
{regimeTrack
? select("value", "Value", regimes.map((k) => ({ value: k, label: s.regimes.find((r) => r.key === k)?.label ?? k })), "—")
: input("value", "Value", s.unit ? `a number in ${s.unit}` : "a number")}
{regimeTrack ? select("event", "Event", s.events.map((e) => ({ value: e, label: e })), "—") : null}
{select("entryId", "Pinned to", view.entries.map((id) => ({ value: id, label: id })), "no entry")}
{input("cite", "Cite", "source second")}
{input("channel", "Channel", "source channel slug")}
{input("video", "Video", "source video id")}
{input("src", "Source", "what it is: a title @ a time")}
{input("scopeBasis", "Basis", "the phrase that settles the scope (never defaulted)")}