#!/usr/bin/env bash
# Read the box's rail state for /prime. Read-only — it opens no mailbox, moves no
# cursor and writes nothing on either machine.
#
# This exists because /prime read `state/last_brief.json` and `state/cursors/` with
# bare relative paths, which resolve to the LAPTOP. Laptop state froze on 2026-07-29
# when the box took over the brief, so on 2026-08-04 prime reported a rail that had
# run every night for six days as dead. Hand-querying the box each session is how it
# got read wrong in the first place, so the query lives in a file.
#
# The laptop half of prime is deliberately NOT here — local files and Get-ScheduledTask
# need no help. This is only the awkward half.
#
# Usage: bin/prime-state.sh [host]
set -uo pipefail

HOST="${1:-root@134.199.153.159}"
REMOTE="/root/personal-cos"

# ONE connection, same reason as drift-check.sh: two back-to-back ssh calls trip the
# box's rapid-connection limit and produce a red report from a healthy box. Everything
# comes back in one round trip, with a retry behind it.
PAYLOAD=$(cat <<'REMOTE_PAYLOAD'
echo "===BOX-DATE==="
date '+%a %d %b %Y %H:%M:%S %Z'
echo "===BOX-TIMERS==="
systemctl list-timers 'personal-cos*' --all --no-pager 2>&1
echo "===BOX-STATE==="
cd /root/personal-cos 2>/dev/null || { echo "REMOTE ROOT MISSING"; exit 0; }
python3 <<'PY' 2>&1
import collections, datetime, json, pathlib

ROOT = pathlib.Path("/root/personal-cos")
now = datetime.datetime.now(datetime.timezone.utc)
today = datetime.date.today()


def newest(pattern):
    files = sorted(ROOT.glob(pattern))
    return files[-1] if files else None


def rows(path):
    with path.open(encoding="utf-8") as handle:
        for line in handle:
            line = line.strip()
            if line:
                try:
                    yield json.loads(line)
                except ValueError:
                    continue


print("-- last brief")
brief = ROOT / "state" / "last_brief.json"
if brief.exists():
    data = json.loads(brief.read_text(encoding="utf-8"))
    sent = data.get("sent_at_utc")
    age = ""
    if sent:
        stamp = datetime.datetime.fromisoformat(sent)
        age = " (%.1fh ago)" % ((now - stamp).total_seconds() / 3600)
    print("sent_at_utc=%s%s trigger=%s streak=%s"
          % (sent, age, data.get("trigger"), data.get("unattended_streak")))
else:
    print("MISSING state/last_brief.json")

print("-- errors")
# Absent is not broken. Nothing has ever failed on the box, and saying "missing" here
# once read as a fault. Say which it is.
log = ROOT / "logs" / "error.log"
if not log.exists():
    print("no logs/error.log — no failure has ever been recorded")
else:
    cutoff = now - datetime.timedelta(hours=48)
    recent = []
    for line in log.read_text(encoding="utf-8", errors="replace").splitlines():
        if not line.startswith("["):
            continue
        head, _, rest = line[1:].partition("]")
        try:
            stamp = datetime.datetime.fromisoformat(head)
        except ValueError:
            continue
        if stamp >= cutoff:
            recent.append(rest.strip()[:110])
    print("%d entries in last 48h (file has %d bytes)" % (len(recent), log.stat().st_size))
    for entry in recent[-5:]:
        print("   " + entry)

print("-- cursors")
cursors = sorted((ROOT / "state" / "cursors").glob("*.json"))
if not cursors:
    print("MISSING state/cursors/")
for path in cursors:
    data = json.loads(path.read_text(encoding="utf-8"))
    print("%-10s last_uid=%s last_run=%s"
          % (path.stem, data.get("last_uid"), data.get("last_run_utc")))

print("-- collection")
messages = newest("data/messages/*.jsonl")
if messages is None:
    print("MISSING data/messages/")
else:
    counts = collections.Counter(row.get("account", "?") for row in rows(messages))
    print("%s: %s" % (messages.name, dict(counts)))

print("-- findings")
findings = newest("data/findings/*.jsonl")
if findings is None:
    print("MISSING data/findings/")
else:
    buckets = collections.Counter()
    flagged = []
    for row in rows(findings):
        bucket = row.get("bucket", "?")
        buckets[bucket] += 1
        if bucket in ("ACT", "REVIEW"):
            flagged.append((bucket, row.get("account", "?"),
                            (row.get("subject") or "(no subject)")[:70]))
    print("%s: %s" % (findings.name, dict(buckets)))
    for bucket, account, subject in flagged:
        print("   %-6s %-10s %s" % (bucket, account, subject))

print("-- deadlines <60d")
path = ROOT / "data" / "deadlines.jsonl"
if not path.exists():
    print("MISSING data/deadlines.jsonl")
else:
    limit = today + datetime.timedelta(days=60)
    seen = set()
    due = []
    for row in rows(path):
        try:
            when = datetime.date.fromisoformat(row.get("date", ""))
        except ValueError:
            continue
        if not (today <= when <= limit):
            continue
        # The register re-records the same obligation from every message that mentions
        # it, so 23/09 lands twice. Two rows is not two deadlines.
        key = (when, row.get("source_subject", ""))
        if key in seen:
            continue
        seen.add(key)
        due.append((when, row.get("what", ""), (row.get("source_subject") or "")[:64]))
    due.sort()
    print("%d due within 60 days" % len(due))
    for when, what, subject in due[:10]:
        print("   %s  %s | %s" % (when, what, subject))

print("-- voice")
voice = ROOT / "inbox-voice"
if voice.exists():
    print("%d waiting" % len([p for p in voice.iterdir() if p.name != ".gitkeep"]))
else:
    print("no inbox-voice/ on box")
PY
echo "===END==="
REMOTE_PAYLOAD
)

out=""
for attempt in 1 2 3; do
    out=$(printf '%s\n' "$PAYLOAD" | ssh -o BatchMode=yes -o ConnectTimeout=30 "$HOST" bash -s 2>&1 || true)
    case "$out" in *===END===*) break ;; esac
    [ "$attempt" -lt 3 ] && sleep $((attempt * 10))
done

case "$out" in
    *===END===*)
        printf '%s\n' "$out"
        ;;
    *)
        # A box that cannot be read is UNVERIFIED, never "no news". The whole point of
        # this file is that a silent gap got reported as a healthy or a dead rail twice.
        echo "could not read $HOST:$REMOTE after 3 attempts — box state UNVERIFIED"
        printf '%s\n' "$out" | tail -5
        exit 2
        ;;
esac
