"""THE AUDIT LAYER — the immune system's memory.

An append-only, hash-chained ledger that every component writes through.

Design
------
One table, ``audit_ledger``, in the orchestration SQLite file (``JARVIS_DB``):

    seq           monotonic integer, 1, 2, 3, ... (PRIMARY KEY)
    ts            ISO-8601 UTC timestamp
    actor         component name that caused the write
    action        dotted verb, e.g. ``state.transition``, ``memory.claim.created``
    subject_type  'job' | 'signal' | 'opportunity' | 'verification_run' | ...
    subject_id    id of the subject, if any
    payload_json  canonical JSON of the facts
    prev_hash     row_hash of the previous row (64 zeros for the genesis row)
    row_hash      sha256(prev_hash + canonical_json(row fields))

The hash covers seq, ts, actor, action, subject_type, subject_id, payload and
prev_hash — every meaningful field of the row.

Append-only is enforced by the DATABASE, not by convention
-----------------------------------------------------------
Two SQLite triggers raise ``RAISE(ABORT)`` on any UPDATE or DELETE against
``audit_ledger``. A compromised (or merely buggy) code path with a normal
connection cannot rewrite history: the database refuses the statement and the
error is surfaced verbatim.

What the verifier detects
-------------------------
``verify()`` walks the chain in seq order and returns
``{ok, length, first_broken_seq, detail}``. It catches:

  * a MODIFIED row   -> recomputed row_hash != stored row_hash
  * a DELETED row    -> gap in seq, or prev_hash link does not match
  * a REORDERED row  -> seq/hash/link mismatch (seq defines the order, and the
                        hash of each row commits to its own seq and predecessor)

The verifier never repairs anything and never reports ok unless every row
recomputes to exactly the stored hash and every link connects to genesis.
"""

from __future__ import annotations

import contextlib
import hashlib
import json
import logging
import os
import sqlite3
from datetime import datetime, timezone

from .db import LOCK as DB_LOCK
from .db import connect, db_path
from .events import GENESIS, canonical, utcnow

log = logging.getLogger("jarvis.audit")

COMPONENT_NAME = "AuditLayer"
HASH_ALGORITHM = "sha256(prev_hash + canonical_json({seq,ts,actor,action,subject_type,subject_id,payload,prev_hash}))"

LEDGER = "audit_ledger"
SCRATCH = "audit_scratch_demo"

#: The canonical name of a row, exposed as a view so the required field names
#: (id / timestamp / component / event_type / subject / payload / prev_hash /
#: row_hash) exist literally in the database, while the storage columns keep the
#: names the rest of the system already uses (seq / ts / actor / action /
#: subject_type+subject_id). One row, one meaning, two spellings.
EVENTS_VIEW = "audit_events"

VIEW_SQL = """
CREATE VIEW IF NOT EXISTS audit_events AS
SELECT seq AS id,
       ts  AS timestamp,
       actor AS component,
       action AS event_type,
       CASE WHEN subject_id IS NULL THEN subject_type
            ELSE subject_type || ':' || subject_id END AS subject,
       payload_json AS payload,
       prev_hash,
       row_hash
FROM audit_ledger
"""

TRIGGER_UPDATE_SQL = """
CREATE TRIGGER IF NOT EXISTS audit_ledger_no_update
BEFORE UPDATE ON audit_ledger
BEGIN
    SELECT RAISE(ABORT, 'audit_ledger is append-only: UPDATE rejected by trigger audit_ledger_no_update');
END
"""

TRIGGER_DELETE_SQL = """
CREATE TRIGGER IF NOT EXISTS audit_ledger_no_delete
BEFORE DELETE ON audit_ledger
BEGIN
    SELECT RAISE(ABORT, 'audit_ledger is append-only: DELETE rejected by trigger audit_ledger_no_delete');
END
"""

#: Statements are executed one by one (never via executescript, which would
#: commit the caller's transaction) so a ledger write can join an existing
#: transaction atomically.
SCHEMA_STATEMENTS = ["""
CREATE TABLE IF NOT EXISTS audit_ledger (
    seq          INTEGER PRIMARY KEY,
    ts           TEXT NOT NULL,
    actor        TEXT NOT NULL,
    action       TEXT NOT NULL,
    subject_type TEXT NOT NULL,
    subject_id   TEXT,
    payload_json TEXT NOT NULL DEFAULT '{}',
    prev_hash    TEXT NOT NULL,
    row_hash     TEXT NOT NULL
);

""",
"""
CREATE INDEX IF NOT EXISTS idx_audit_actor   ON audit_ledger(actor)
""",
"""
CREATE INDEX IF NOT EXISTS idx_audit_action  ON audit_ledger(action)
""",
"""
CREATE INDEX IF NOT EXISTS idx_audit_subject ON audit_ledger(subject_type, subject_id)
""",
"""
CREATE TABLE IF NOT EXISTS audit_meta (
    key   TEXT PRIMARY KEY,
    value TEXT NOT NULL
)
""",
VIEW_SQL,
# Append-only, enforced by SQLite itself. Not a convention, not a code path.
TRIGGER_UPDATE_SQL,
TRIGGER_DELETE_SQL,
]



#: A scratch copy of the ledger used ONLY to demonstrate that tampering is
#: detectable. It intentionally has no triggers so that the demo can corrupt it.
SCRATCH_SCHEMA = """
CREATE TABLE IF NOT EXISTS __TABLE__ (
    seq          INTEGER PRIMARY KEY,
    ts           TEXT NOT NULL,
    actor        TEXT NOT NULL,
    action       TEXT NOT NULL,
    subject_type TEXT NOT NULL,
    subject_id   TEXT,
    payload_json TEXT NOT NULL DEFAULT '{}',
    prev_hash    TEXT NOT NULL,
    row_hash     TEXT NOT NULL
);
"""


# --------------------------------------------------------------------------
# hashing
# --------------------------------------------------------------------------

def row_body(seq: int, ts: str, actor: str, action: str, subject_type: str,
             subject_id, payload_json: str, prev_hash: str) -> dict:
    """The exact field set that is hashed. Keep in sync with ``compute_row_hash``."""
    try:
        payload = json.loads(payload_json) if payload_json else {}
    except (TypeError, ValueError):
        # An unparseable payload is hashed by its raw bytes below; the verifier
        # reports that row as broken rather than silently accepting it.
        payload = {"__unparseable_payload__": payload_json}
    return {
        "seq": seq,
        "ts": ts,
        "actor": actor,
        "action": action,
        "subject_type": subject_type,
        "subject_id": subject_id,
        "payload": payload,
        "prev_hash": prev_hash,
    }


def compute_row_hash(prev_hash: str, body: dict) -> str:
    return hashlib.sha256((prev_hash + canonical(body)).encode("utf-8")).hexdigest()


# --------------------------------------------------------------------------
# schema
# --------------------------------------------------------------------------

#: Every object the ledger depends on. A partially-initialised database (e.g. a
#: ledger table created by an older build, or a hand-made file) must still get
#: its meta table and its append-only triggers, so the check is per-object and
#: not "does the ledger table exist?".
REQUIRED_OBJECTS = [
    ("table", LEDGER),
    ("table", "audit_meta"),
    ("view", EVENTS_VIEW),
    ("trigger", "audit_ledger_no_update"),
    ("trigger", "audit_ledger_no_delete"),
]


def _ensure(conn: sqlite3.Connection) -> None:
    """Idempotent, cheap, and safe inside a caller's transaction.

    One sqlite_master lookup on the hot path; DDL only when something is absent.
    (``executescript`` is deliberately avoided: it would commit the caller's
    transaction before the ledger row was written.)
    """
    present = {
        (r["type"], r["name"])
        for r in conn.execute(
            "SELECT type, name FROM sqlite_master WHERE name IN (?,?,?,?,?)",
            (LEDGER, "audit_meta", EVENTS_VIEW,
             "audit_ledger_no_update", "audit_ledger_no_delete"),
        ).fetchall()
    }
    if all(obj in present for obj in REQUIRED_OBJECTS):
        return
    for statement in SCHEMA_STATEMENTS:
        conn.execute(statement)


def _triggers(conn: sqlite3.Connection) -> list[str]:
    return [
        r["name"]
        for r in conn.execute(
            "SELECT name FROM sqlite_master WHERE type='trigger' AND tbl_name=? ORDER BY name",
            (LEDGER,),
        ).fetchall()
    ]


def init_db() -> str:
    """Create the ledger + triggers if missing, then mirror legacy events once.

    The old ``events`` table keeps working exactly as before. On first run of
    the audit layer, every pre-existing event row is copied into the ledger
    (action ``event.mirror``) so nothing written before this feature existed is
    lost; the watermark is stored in ``audit_meta`` so it happens only once.
    """
    with DB_LOCK:
        conn = connect()
        try:
            _ensure(conn)
            conn.commit()
            mirror_legacy_events(conn)
        finally:
            conn.close()
    return db_path()


def _meta_get(conn, key: str):
    row = conn.execute("SELECT value FROM audit_meta WHERE key = ?", (key,)).fetchone()
    return row["value"] if row else None


def _meta_set(conn, key: str, value: str) -> None:
    conn.execute(
        "INSERT INTO audit_meta (key, value) VALUES (?,?) "
        "ON CONFLICT(key) DO UPDATE SET value = excluded.value",
        (key, str(value)),
    )


def mirror_legacy_events(conn: sqlite3.Connection) -> int:
    """Copy the old hash-chained ``events`` rows into the ledger, exactly once.

    These are real historical rows, not fabricated ones: each ledger row carries
    the original event id, kind and hash in its payload, marked ``migrated``.
    """
    if _meta_get(conn, "events_mirrored_upto") is not None:
        return 0
    tables = {
        r["name"]
        for r in conn.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()
    }
    if "events" not in tables:
        _meta_set(conn, "events_mirrored_upto", "0")
        conn.commit()
        return 0
    rows = conn.execute("SELECT * FROM events ORDER BY id ASC").fetchall()
    mirrored = 0
    for row in rows:
        d = dict(row)
        _append(
            conn,
            actor=d["actor"],
            action=f"event.mirror.{d['kind']}",
            subject_type="event",
            subject_id=str(d["id"]),
            payload={
                "migrated": True,
                "source": "events",
                "event_id": d["id"],
                "kind": d["kind"],
                "job_id": d.get("job_id"),
                "from_state": d.get("from_state"),
                "to_state": d.get("to_state"),
                "note": d.get("note"),
                "event_hash": d.get("hash"),
                "event_prev_hash": d.get("prev_hash"),
                "event_ts": d.get("ts"),
            },
            ts=d["ts"],
        )
        mirrored += 1
    _meta_set(conn, "events_mirrored_upto", str(rows[-1]["id"] if rows else 0))
    conn.commit()
    if mirrored:
        log.info("audit: mirrored %d pre-existing event(s) into the ledger", mirrored)
    return mirrored


# --------------------------------------------------------------------------
# append
# --------------------------------------------------------------------------

def _head(conn: sqlite3.Connection) -> tuple[int, str]:
    row = conn.execute(
        f"SELECT seq, row_hash FROM {LEDGER} ORDER BY seq DESC LIMIT 1"
    ).fetchone()
    if row is None:
        return 0, GENESIS
    return int(row["seq"]), row["row_hash"]


def _append(conn: sqlite3.Connection, *, actor: str, action: str, subject_type: str,
            subject_id, payload, ts: str | None = None) -> dict:
    """Append one row on an already-open connection. Caller owns the transaction."""
    actor = str(actor or "unknown")
    action = str(action or "unknown")
    subject_type = str(subject_type or "unknown")
    subject_id = None if subject_id is None else str(subject_id)
    payload_json = canonical(payload if payload is not None else {})
    ts = ts or utcnow()
    seq, prev = _head(conn)
    seq += 1
    body = row_body(seq, ts, actor, action, subject_type, subject_id, payload_json, prev)
    row_hash = compute_row_hash(prev, body)
    conn.execute(
        f"""INSERT INTO {LEDGER}
            (seq, ts, actor, action, subject_type, subject_id, payload_json, prev_hash, row_hash)
            VALUES (?,?,?,?,?,?,?,?,?)""",
        (seq, ts, actor, action, subject_type, subject_id, payload_json, prev, row_hash),
    )
    return {
        "seq": seq,
        "ts": ts,
        "actor": actor,
        "action": action,
        "subject_type": subject_type,
        "subject_id": subject_id,
        "payload_json": payload_json,
        "prev_hash": prev,
        "row_hash": row_hash,
    }


def _project_legacy(conn: sqlite3.Connection, *, actor: str, legacy: dict) -> dict:
    """Write the job-centric row into the legacy ``events`` table.

    This is the *only* place the old table is written from application code: the
    projection is produced by the audit layer as part of the same transaction as
    the ledger row, so the two can never disagree and there is no second write
    path to keep in sync. ``events`` stays readable (and verifiable) for every
    existing endpoint; it is simply no longer written independently.
    """
    from .events import append_event  # local import: events must not import audit

    return append_event(
        conn,
        job_id=legacy.get("job_id"),
        actor=actor,
        kind=legacy["kind"],
        from_state=legacy.get("from_state"),
        to_state=legacy.get("to_state"),
        note=legacy.get("note", ""),
        data=legacy.get("data"),
    )


def record(actor: str, action: str, subject_type: str, subject_id=None, payload=None,
           conn: sqlite3.Connection | None = None, legacy: dict | None = None) -> dict:
    """THE single write path into the ledger — and therefore into the system.

    Every component calls this: the orchestrator's state transitions, ingestion
    runs, opportunity creation, verification verdicts and memory writes.

    Pass ``conn`` when already inside a transaction on the orchestration DB so the
    ledger row commits or rolls back atomically with the fact it records.

    ``legacy`` optionally describes the same fact in the shape the pre-existing
    job-centric ``events`` log uses (``kind``, ``job_id``, ``from_state``,
    ``to_state``, ``note``, ``data``). It is *not* a second write: the audit layer
    projects the row into ``events`` itself, on the caller's connection, and
    returns it under the ``legacy_event`` key.

    ``ts`` is only supplied when replaying real, pre-existing rows (migration).
    """
    _tid = _resolve_trace_id()
    if _tid:
        payload = _merge_trace(payload, _tid)
    if conn is not None:
        _ensure(conn)
        event = _project_legacy(conn, actor=actor, legacy=legacy) if legacy else None
        row = _append(conn, actor=actor, action=action, subject_type=subject_type,
                      subject_id=subject_id, payload=payload)
        row["legacy_event"] = event
        return row
    with DB_LOCK:
        own = connect()
        try:
            _ensure(own)
            own.commit()
            own.execute("BEGIN IMMEDIATE")
            event = _project_legacy(own, actor=actor, legacy=legacy) if legacy else None
            row = _append(own, actor=actor, action=action, subject_type=subject_type,
                          subject_id=subject_id, payload=payload)
            row["legacy_event"] = event
            own.commit()
            return row
        except Exception:
            own.rollback()
            raise
        finally:
            own.close()


# --------------------------------------------------------------------------
# verification
# --------------------------------------------------------------------------

def _decode_row(row) -> tuple[dict, str | None]:
    """Return the canonical body for a stored row, or (partial, error)."""
    d = dict(row)
    payload_json = d.get("payload_json") or "{}"
    try:
        json.loads(payload_json)
    except (TypeError, ValueError) as exc:
        return d, f"payload_json is not valid JSON at seq {d.get('seq')}: {exc}"
    body = {
        "seq": d["seq"],
        "ts": d["ts"],
        "actor": d["actor"],
        "action": d["action"],
        "subject_type": d["subject_type"],
        "subject_id": d["subject_id"],
        "payload": json.loads(payload_json),
        "prev_hash": d["prev_hash"],
    }
    return body, None


def _verify_result(ok: bool, length: int, broken_at, detail: str, table: str,
                   head_hash, checked_at: str) -> dict:
    """One shape for every answer.

    ``ok``/``length`` are the whole story on success. On failure the REQUIRED
    contract is ``{ok: false, broken_at: <row id>, reason: "..."}``; the older
    ``first_broken_seq``/``detail`` spellings are kept next to them so the
    existing callers and pages keep working unchanged.
    """
    return {
        "ok": bool(ok),
        "length": int(length),
        # --- canonical contract (requirement) -------------------------------
        "broken_at": broken_at,
        "reason": detail if not ok else None,
        # --- back-compatible aliases (existing UI/tests) --------------------
        "first_broken_seq": broken_at,
        "detail": detail,
        "checked_at": checked_at,
        "table": table,
        "head_hash": head_hash,
        "genesis": GENESIS,
        "algorithm": HASH_ALGORITHM,
    }


def verify_conn(conn: sqlite3.Connection, table: str = LEDGER) -> dict:
    """Recompute an entire chain from genesis. Never mutates anything."""
    checked_at = utcnow()
    try:
        rows = conn.execute(f"SELECT * FROM {table} ORDER BY seq ASC").fetchall()
    except sqlite3.Error as exc:
        return _verify_result(False, 0, None, f"cannot read {table}: {exc}", table,
                              None, checked_at)

    expected_seq = 1
    prev = GENESIS
    for row in rows:
        seq = row["seq"]
        body, decode_error = _decode_row(row)
        if decode_error:
            return _verify_result(False, len(rows), seq, decode_error, table,
                                  None, checked_at)
        if seq != expected_seq:
            if seq > expected_seq:
                detail = (
                    f"seq gap at {expected_seq}: expected seq {expected_seq} but found {seq} "
                    f"— {seq - expected_seq} row(s) missing (deleted)"
                )
                broken = expected_seq
            else:
                detail = f"seq out of order: expected {expected_seq}, found {seq} (reordered/duplicated row)"
                broken = seq
            return _verify_result(False, len(rows), broken, detail, table, None, checked_at)
        if row["prev_hash"] != prev:
            return _verify_result(
                False, len(rows), seq,
                (f"prev_hash mismatch at seq {seq}: row links to {row['prev_hash'][:16]}… "
                 f"but the chain head is {prev[:16]}… (row deleted, reordered or replaced)"),
                table, None, checked_at,
            )
        expected = compute_row_hash(prev, body)
        if expected != row["row_hash"]:
            return _verify_result(
                False, len(rows), seq,
                (f"hash mismatch at seq {seq}: stored {row['row_hash'][:16]}… "
                 f"recomputes to {expected[:16]}… (row content was modified)"),
                table, None, checked_at,
            )
        prev = row["row_hash"]
        expected_seq += 1

    return _verify_result(
        True, len(rows), None,
        (f"all {len(rows)} row(s) recomputed and linked to genesis"
         if rows else "ledger is empty: chain trivially valid"),
        table, prev, checked_at,
    )


def verify() -> dict:
    """Verify the REAL ledger (GET /audit/verify)."""
    conn = connect()
    try:
        _ensure(conn)
        return verify_conn(conn, LEDGER)
    finally:
        conn.close()


# --------------------------------------------------------------------------
# reads for the UI / API
# --------------------------------------------------------------------------

def _row_view(row, full_hash: bool = False) -> dict:
    d = {
        "seq": row["seq"],
        "ts": row["ts"],
        "actor": row["actor"],
        "action": row["action"],
        "subject_type": row["subject_type"],
        "subject_id": row["subject_id"],
        "prev_hash": row["prev_hash"],
        "row_hash": row["row_hash"],
        "row_hash_short": (row["row_hash"][:12] + "…") if row["row_hash"] else "",
    }
    try:
        d["payload"] = json.loads(row["payload_json"] or "{}")
    except (TypeError, ValueError):
        d["payload"] = {"__raw__": row["payload_json"]}
    if not full_hash:
        d.pop("prev_hash")
    return d


def recent(limit: int = 100, actor: str | None = None, action: str | None = None,
           subject: str | None = None) -> list[dict]:
    """Newest-first rows, optionally filtered by component (actor) and event type.

    Filters are exact matches except ``subject``, which matches any row whose
    subject_id equals it OR whose payload mentions it (so a job id, an
    opportunity id or a run id all work).
    """
    limit = max(1, min(int(limit), 1000))
    sql = f"SELECT * FROM {LEDGER}"
    where, args = [], []
    if actor:
        where.append("actor = ?")
        args.append(actor)
    if action:
        where.append("action = ?")
        args.append(action)
    if subject:
        where.append("(subject_id = ? OR payload_json LIKE ?)")
        args.extend([subject, f"%{subject}%"])
    if where:
        sql += " WHERE " + " AND ".join(where)
    sql += " ORDER BY seq DESC LIMIT ?"
    args.append(limit)
    conn = connect()
    try:
        _ensure(conn)
        rows = conn.execute(sql, tuple(args)).fetchall()
        return [_row_view(r) for r in rows]
    finally:
        conn.close()


def facets() -> dict:
    """The real distinct component / event_type values, for the filter dropdowns."""
    conn = connect()
    try:
        _ensure(conn)
        actors = [
            {"value": r["actor"], "count": r["n"]}
            for r in conn.execute(
                f"SELECT actor, COUNT(*) AS n FROM {LEDGER} GROUP BY actor ORDER BY n DESC, actor ASC"
            ).fetchall()
        ]
        actions = [
            {"value": r["action"], "count": r["n"]}
            for r in conn.execute(
                f"SELECT action, COUNT(*) AS n FROM {LEDGER} GROUP BY action ORDER BY n DESC, action ASC"
            ).fetchall()
        ]
        return {"components": actors, "event_types": actions}
    finally:
        conn.close()


def trace(subject: str, limit: int = 500) -> dict:
    """Every ledger row that touches one subject, in chain order.

    This is the provenance trail: given an opportunity id or a job id you get the
    whole ordered story of what the system did about it — not a summary, the rows
    themselves, each with its hash so any single step can be checked.
    """
    subject = str(subject or "").strip()
    if not subject:
        return {"subject": subject, "count": 0, "events": [], "verify": verify()}
    limit = max(1, min(int(limit), 2000))
    conn = connect()
    try:
        _ensure(conn)
        rows = conn.execute(
            f"""SELECT * FROM {LEDGER}
                WHERE subject_id = ? OR payload_json LIKE ?
                ORDER BY seq ASC LIMIT ?""",
            (subject, f"%{subject}%", limit),
        ).fetchall()
        events = [_row_view(r, full_hash=True) for r in rows]
    finally:
        conn.close()
    return {
        "subject": subject,
        "count": len(events),
        "events": events,
        "first_seq": events[0]["seq"] if events else None,
        "last_seq": events[-1]["seq"] if events else None,
        "components": sorted({e["actor"] for e in events}),
        "event_types": sorted({e["action"] for e in events}),
        "verify": verify(),
    }


def counts() -> dict:
    conn = connect()
    try:
        _ensure(conn)
        total = conn.execute(f"SELECT COUNT(*) AS n FROM {LEDGER}").fetchone()["n"]
        actors = [
            dict(r)
            for r in conn.execute(
                f"SELECT actor, COUNT(*) AS n FROM {LEDGER} GROUP BY actor ORDER BY n DESC"
            ).fetchall()
        ]
        return {"length": total, "actors": actors}
    finally:
        conn.close()


def head() -> dict:
    """The current tip of the chain (what the badge shows as 'last hash')."""
    conn = connect()
    try:
        _ensure(conn)
        row = conn.execute(
            f"SELECT seq, ts, row_hash FROM {LEDGER} ORDER BY seq DESC LIMIT 1"
        ).fetchone()
        if row is None:
            return {"seq": 0, "ts": None, "row_hash": GENESIS, "is_genesis": True}
        return {"seq": row["seq"], "ts": row["ts"], "row_hash": row["row_hash"],
                "is_genesis": False}
    finally:
        conn.close()


def status() -> dict:
    """One call for the UI badge: verified/broken + real length + head hash."""
    result = verify()
    result["component"] = COMPONENT_NAME
    result["table"] = LEDGER
    if result.get("head_hash") is None:
        result["head_hash"] = head()["row_hash"]
    return result


# --------------------------------------------------------------------------
# tamper test — real, not simulated
# --------------------------------------------------------------------------

def _attempt(conn_factory, label: str, sql: str, params: tuple = ()) -> dict:
    """Run a forbidden statement on a REAL connection and capture the DB's answer."""
    conn = conn_factory()
    try:
        cur = conn.execute(sql, params)
        conn.commit()
        changed = cur.rowcount
        return {
            "operation": label,
            "sql": sql,
            "blocked": False,
            "rows_affected": changed,
            "error_type": None,
            "error": None,
            "note": "NOT BLOCKED — the database allowed this write. This is a real failure.",
        }
    except sqlite3.Error as exc:
        try:
            conn.rollback()
        except sqlite3.Error:
            pass
        return {
            "operation": label,
            "sql": sql,
            "blocked": True,
            "rows_affected": 0,
            "error_type": type(exc).__name__,
            "error": str(exc),
            "note": "Rejected by the SQLite trigger; nothing was written.",
        }
    finally:
        conn.close()


def _scratch_copy(conn: sqlite3.Connection, table: str = SCRATCH) -> int:
    """Copy the real ledger into a throwaway table. Returns the copied length."""
    conn.executescript(SCRATCH_SCHEMA.replace("__TABLE__", table))
    conn.execute(f"DELETE FROM {table}")
    cur = conn.execute(
        f"""INSERT INTO {table}
            (seq, ts, actor, action, subject_type, subject_id, payload_json, prev_hash, row_hash)
            SELECT seq, ts, actor, action, subject_type, subject_id, payload_json, prev_hash, row_hash
            FROM {LEDGER} ORDER BY seq ASC"""
    )
    conn.commit()
    return cur.rowcount


def _scratch_pad(conn: sqlite3.Connection, table: str, want: int = 5) -> int:
    """Extend the SCRATCH copy with valid, clearly-labelled synthetic rows.

    Only ever touches the scratch table. Needed so the modify/delete/reorder
    demonstrations have enough rows to be meaningful on a young ledger. Each
    padded row is hashed with the real algorithm and marked ``synthetic: true``
    in its payload, so nothing about it can be mistaken for a real event.
    """
    rows = conn.execute(f"SELECT * FROM {table} ORDER BY seq ASC").fetchall()
    if not rows:
        return 0
    seq = int(rows[-1]["seq"])
    prev = rows[-1]["row_hash"]
    added = 0
    while seq < want:
        seq += 1
        ts = utcnow()
        payload_json = canonical({
            "synthetic": True,
            "reason": "scratch-only padding so the tamper demo has enough rows",
            "note": "this row exists ONLY in the scratch demo table, never in audit_ledger",
        })
        body = row_body(seq, ts, COMPONENT_NAME, "audit.scratch.padding",
                        "audit_scratch", str(seq), payload_json, prev)
        row_hash = compute_row_hash(prev, body)
        conn.execute(
            f"""INSERT INTO {table}
                (seq, ts, actor, action, subject_type, subject_id, payload_json, prev_hash, row_hash)
                VALUES (?,?,?,?,?,?,?,?,?)""",
            (seq, ts, COMPONENT_NAME, "audit.scratch.padding", "audit_scratch",
             str(seq), payload_json, prev, row_hash),
        )
        prev = row_hash
        added += 1
    conn.commit()
    return added


def tamper_test() -> dict:
    """Prove, with real database responses, that tampering is blocked and detectable.

    Steps:
      1. append one genuine ledger row saying the test ran;
      2. attempt UPDATE and DELETE against the REAL ledger through a normal
         connection and capture SQLite's actual error text;
      3. copy the ledger into a scratch table and corrupt the copy three ways
         (modify / delete / reorder), reporting the exact seq where the verifier
         breaks for each;
      4. re-verify the REAL ledger and report the actual ok/length.

    The real ledger is never modified or deleted from.
    """
    started = utcnow()
    before = verify()

    record(
        COMPONENT_NAME,
        "audit.tamper_test.started",
        "audit_ledger",
        str(before["length"]),
        {
            "started_at": started,
            "real_length_before": before["length"],
            "real_ok_before": before["ok"],
            "intent": "attempt UPDATE + DELETE on the real ledger; corrupt only a scratch copy",
        },
    )

    target = 1
    blocked = [
        _attempt(
            connect,
            f"UPDATE {LEDGER} SET actor='tampered' WHERE seq={target}",
            f"UPDATE {LEDGER} SET actor='tampered' WHERE seq = ?", (target,),
        ),
        _attempt(
            connect,
            f"DELETE FROM {LEDGER} WHERE seq={target}",
            f"DELETE FROM {LEDGER} WHERE seq = ?", (target,),
        ),
    ]

    mid = verify()

    scratch_result: dict = {"table": SCRATCH, "cases": []}
    conn = connect()

    def reset_scratch() -> list[int]:
        """Rebuild the scratch table from the real ledger and pad it to >=5 rows.

        Returns the seq list of the fresh copy. Only ever touches SCRATCH.
        """
        copied = _scratch_copy(conn, SCRATCH)
        padded = _scratch_pad(conn, SCRATCH, want=5)
        scratch_result["copied_rows"] = copied
        scratch_result["padded_rows"] = scratch_result.get("padded_rows", 0) + padded
        return [
            r["seq"] for r in conn.execute(
                f"SELECT seq FROM {SCRATCH} ORDER BY seq ASC"
            ).fetchall()
        ]

    try:
        _ensure(conn)
        seqs = reset_scratch()

        if len(seqs) >= 2:
            mid_idx = len(seqs) // 2

            # --- case 1: modified row in the scratch copy -------------------
            modify_seq = seqs[mid_idx]
            conn.execute(
                f"UPDATE {SCRATCH} SET actor = ?, payload_json = ? WHERE seq = ?",
                ("intruder", canonical({"forged": True, "tamper": "payload rewritten"}), modify_seq),
            )
            conn.commit()
            modified = verify_conn(conn, SCRATCH)
            scratch_result["cases"].append({
                "case": "modified_row",
                "what": f"UPDATE {SCRATCH} SET actor='intruder', payload_json='{{\"forged\":true,…}}' WHERE seq={modify_seq}",
                "corrupted_seq": modify_seq,
                "verify": modified,
                "caught": not modified["ok"],
            })

            # --- case 2: deleted row in the scratch copy -------------------
            seqs = reset_scratch()
            delete_seq = seqs[len(seqs) // 2]
            conn.execute(f"DELETE FROM {SCRATCH} WHERE seq = ?", (delete_seq,))
            conn.commit()
            deleted = verify_conn(conn, SCRATCH)
            scratch_result["cases"].append({
                "case": "deleted_row",
                "what": f"DELETE FROM {SCRATCH} WHERE seq={delete_seq}",
                "corrupted_seq": delete_seq,
                "verify": deleted,
                "caught": not deleted["ok"],
            })

            # --- case 3: reordered rows in the scratch copy ----------------
            seqs = reset_scratch()
            a = seqs[len(seqs) // 2]
            b = seqs[len(seqs) // 2 + 1] if len(seqs) > len(seqs) // 2 + 1 else None
            if b is not None:
                row_a = dict(conn.execute(f"SELECT * FROM {SCRATCH} WHERE seq=?", (a,)).fetchone())
                row_b = dict(conn.execute(f"SELECT * FROM {SCRATCH} WHERE seq=?", (b,)).fetchone())
                # swap the two rows' contents while keeping their seq values,
                # which is exactly what a reorder looks like to the chain
                for target_seq, src_row in ((a, row_b), (b, row_a)):
                    conn.execute(
                        f"UPDATE {SCRATCH} SET ts=?, actor=?, action=?, subject_type=?, subject_id=?,"
                        f" payload_json=?, prev_hash=?, row_hash=? WHERE seq=?",
                        (src_row["ts"], src_row["actor"], src_row["action"], src_row["subject_type"],
                         src_row["subject_id"], src_row["payload_json"], src_row["prev_hash"],
                         src_row["row_hash"], target_seq),
                    )
                conn.commit()
                reordered = verify_conn(conn, SCRATCH)
                scratch_result["cases"].append({
                    "case": "reordered_rows",
                    "what": f"swapped the contents of seq {a} and seq {b} in {SCRATCH}",
                    "corrupted_seq": a,
                    "verify": reordered,
                    "caught": not reordered["ok"],
                })
        else:
            scratch_result["error"] = (
                f"scratch copy had only {len(seqs)} row(s); need >=2 to demonstrate corruption"
            )
    finally:
        conn.close()

    after = verify()
    record(
        COMPONENT_NAME,
        "audit.tamper_test.finished",
        "audit_ledger",
        str(after["length"]),
        {
            "started_at": started,
            "finished_at": utcnow(),
            "update_blocked": blocked[0]["blocked"],
            "delete_blocked": blocked[1]["blocked"],
            "scratch_cases_caught": [c["case"] for c in scratch_result.get("cases", []) if c["caught"]],
            "real_ok_after": after["ok"],
            "real_length_after": after["length"],
        },
    )
    final = verify()

    all_blocked = all(b["blocked"] for b in blocked)
    cases = scratch_result.get("cases", [])
    all_caught = bool(cases) and all(c["caught"] for c in cases)
    if not cases:
        scratch_result["error"] = (
            "the scratch copy had fewer than 2 rows, so no corruption case could be "
            "demonstrated; this is reported as a failure rather than a pass"
        )
    return {
        "ok": bool(all_blocked and all_caught and final["ok"]),
        "started_at": started,
        "finished_at": utcnow(),
        "real_ledger_before": before,
        "blocked_operations": blocked,
        "real_verify_after_attempts": mid,
        "scratch": scratch_result,
        "real_ledger_after": final,
        "real_ledger_intact": final["ok"],
        "verdict": (
            f"UPDATE blocked={blocked[0]['blocked']}, DELETE blocked={blocked[1]['blocked']}, "
            f"scratch tamper cases caught={sum(1 for c in scratch_result.get('cases', []) if c['caught'])}"
            f"/{len(scratch_result.get('cases', []))}, "
            f"real ledger after={('ok:' + str(final['ok']) + ' length:' + str(final['length']))}"
        ),
    }


# ==========================================================================
# DEV-ONLY TAMPER INJECTION — DO NOT USE THIS PATH FOR ANYTHING REAL
# ==========================================================================
#
# The append-only triggers above are the production guarantee: a normal
# connection cannot rewrite the ledger. That is exactly what makes the immune
# system worth having — and exactly what makes it impossible to *demonstrate*
# the verifier catching a real tamper, because nothing can tamper.
#
# So this section is a deliberate, clearly-labelled escape hatch that exists
# ONLY for the "tamper demo" on the Audit tab and for the test suite:
#
#   * it is guarded by JARVIS_ALLOW_TAMPER (default on; set "0" to disable);
#   * the HTTP route that exposes it is /audit/_tamper, prefixed with an
#     underscore and marked DEV-ONLY in the UI and in this comment;
#   * every use appends an honest "audit.tamper.injected" row to the ledger
#     BEFORE the damage is done, so the ledger itself records that the demo ran;
#   * the original row is snapshotted in audit_meta so dev_restore() can put the
#     chain back exactly as it was — the demo leaves a healthy chain behind.
#
# Nothing here is reachable from a component: no ingestion run, no opportunity
# engine, no verification run and no memory write can call these functions.

DEV_TAMPER_ENV = "JARVIS_ALLOW_TAMPER"
DEV_ACTOR = "AuditDevTools"
DEV_SNAPSHOT_KEY = "dev_tamper_snapshot"

#: Columns the demo is allowed to corrupt. Anything else is refused outright.
TAMPERABLE_FIELDS = ("actor", "action", "subject_type", "subject_id", "ts",
                     "payload_json", "prev_hash", "row_hash")


def dev_tamper_enabled() -> bool:
    """True unless JARVIS_ALLOW_TAMPER is explicitly switched off."""
    raw = os.environ.get(DEV_TAMPER_ENV, "1").strip().lower()
    return raw not in ("0", "false", "no", "off")


def _dev_disabled() -> dict:
    return {
        "ok": False,
        "applied": False,
        "dev_only": True,
        "error": (
            f"dev tamper injection is disabled: {DEV_TAMPER_ENV} is set to "
            f"{os.environ.get(DEV_TAMPER_ENV)!r}"
        ),
        "note": "Nothing was modified. This endpoint is a dev-only demonstration.",
    }


@contextlib.contextmanager
def _triggers_suspended(conn: sqlite3.Connection):
    """Temporarily drop the append-only triggers, then always put them back.

    This is the whole "bypassing the chain" step of the demo: the row is edited
    with plain SQL while the guards are off, exactly like an attacker (or a
    compromised process) with write access to the file would do. The verifier
    has no idea any of this happened — it only reads bytes.
    """
    conn.execute("DROP TRIGGER IF EXISTS audit_ledger_no_update")
    conn.execute("DROP TRIGGER IF EXISTS audit_ledger_no_delete")
    try:
        yield
    finally:
        conn.execute(TRIGGER_UPDATE_SQL)
        conn.execute(TRIGGER_DELETE_SQL)


def _snapshots(conn: sqlite3.Connection) -> dict:
    raw = _meta_get(conn, DEV_SNAPSHOT_KEY)
    if not raw:
        return {}
    try:
        return json.loads(raw)
    except (TypeError, ValueError):
        return {}


def _save_snapshot(conn: sqlite3.Connection, seq: int, row: dict) -> None:
    snaps = _snapshots(conn)
    snaps[str(seq)] = row
    _meta_set(conn, DEV_SNAPSHOT_KEY, canonical(snaps))


def dev_state() -> dict:
    """What the dev demo has corrupted right now (empty when nothing is)."""
    conn = connect()
    try:
        _ensure(conn)
        snaps = _snapshots(conn)
        return {
            "dev_only": True,
            "enabled": dev_tamper_enabled(),
            "env_flag": DEV_TAMPER_ENV,
            "tampered_rows": sorted(int(s) for s in snaps),
            "restorable": bool(snaps),
        }
    finally:
        conn.close()


def dev_tamper(row_id: int, field: str = "payload_json", value=None) -> dict:
    """DEV-ONLY: mutate one REAL ledger row directly in SQLite, behind the chain.

    The hash chain is not recomputed, the row_hash is left stale, and the
    triggers are suspended for the duration of the single UPDATE. That is a real
    tamper, not a simulated one: GET /audit/verify must now fail and name this
    exact row.
    """
    if not dev_tamper_enabled():
        return _dev_disabled()
    field = (field or "payload_json").strip()
    if field not in TAMPERABLE_FIELDS:
        return {
            "ok": False, "applied": False, "dev_only": True,
            "error": f"field {field!r} is not tamperable; choose one of {', '.join(TAMPERABLE_FIELDS)}",
        }
    try:
        row_id = int(row_id)
    except (TypeError, ValueError):
        return {"ok": False, "applied": False, "dev_only": True,
                "error": f"row id {row_id!r} is not an integer"}

    conn = connect()
    try:
        _ensure(conn)
        row = conn.execute(f"SELECT * FROM {LEDGER} WHERE seq = ?", (row_id,)).fetchone()
        if row is None:
            return {"ok": False, "applied": False, "dev_only": True,
                    "error": f"no ledger row with seq {row_id}",
                    "length": conn.execute(f"SELECT COUNT(*) AS n FROM {LEDGER}").fetchone()["n"]}

        original = dict(row)
        if value is None:
            if field == "payload_json":
                try:
                    parsed = json.loads(original["payload_json"] or "{}")
                except (TypeError, ValueError):
                    parsed = {"__raw__": original["payload_json"]}
                new_value = canonical({
                    "tampered": True,
                    "dev_only": True,
                    "injected_by": "POST /audit/_tamper",
                    "replaced_payload": parsed,
                })
            elif field == "prev_hash":
                new_value = "f" * 64
            else:
                new_value = f"tampered-{field}"
        else:
            new_value = str(value)

        # 1) record the demo honestly, while the chain is still valid
        intent = _append(
            conn,
            actor=DEV_ACTOR,
            action="audit.tamper.injected",
            subject_type="audit_ledger",
            subject_id=str(row_id),
            payload={
                "dev_only": True,
                "row_id": row_id,
                "field": field,
                "original_value": str(original[field]),
                "new_value": new_value,
                "method": "UPDATE on audit_ledger with the append-only triggers suspended",
                "warning": "this row records a deliberate, dev-only corruption of the ledger",
            },
        )
        # 2) remember the real row so dev_restore() can put it back byte for byte
        _save_snapshot(conn, row_id, original)
        # 3) do the actual damage with the guards off
        with _triggers_suspended(conn):
            conn.execute(
                f"UPDATE {LEDGER} SET {field} = ? WHERE seq = ?", (new_value, row_id)
            )
        conn.commit()
    except sqlite3.Error as exc:
        conn.rollback()
        return {"ok": False, "applied": False, "dev_only": True,
                "error": f"sqlite refused the tamper: {exc}"}
    finally:
        conn.close()

    return {
        "ok": True,
        "applied": True,
        "dev_only": True,
        "row_id": row_id,
        "field": field,
        "original_value": str(original[field]),
        "new_value": new_value,
        "intent_seq": intent["seq"],
        "intent": "row content mutated with plain SQL; row_hash deliberately NOT recomputed",
        "verify": verify(),
    }


def dev_delete(row_id: int) -> dict:
    """DEV-ONLY: delete one REAL ledger row, leaving a hole in the chain.

    Used by the test suite (and available to the demo) to prove the verifier
    reports a deleted row at the exact id where the hole is.
    """
    if not dev_tamper_enabled():
        return _dev_disabled()
    try:
        row_id = int(row_id)
    except (TypeError, ValueError):
        return {"ok": False, "applied": False, "dev_only": True,
                "error": f"row id {row_id!r} is not an integer"}

    conn = connect()
    try:
        _ensure(conn)
        row = conn.execute(f"SELECT * FROM {LEDGER} WHERE seq = ?", (row_id,)).fetchone()
        if row is None:
            return {"ok": False, "applied": False, "dev_only": True,
                    "error": f"no ledger row with seq {row_id}"}
        original = dict(row)
        intent = _append(
            conn,
            actor=DEV_ACTOR,
            action="audit.tamper.deleted",
            subject_type="audit_ledger",
            subject_id=str(row_id),
            payload={
                "dev_only": True,
                "row_id": row_id,
                "deleted_row": {k: original[k] for k in original},
                "method": "DELETE FROM audit_ledger with the append-only triggers suspended",
                "warning": "this row records a deliberate, dev-only deletion from the ledger",
            },
        )
        _save_snapshot(conn, row_id, original)
        with _triggers_suspended(conn):
            conn.execute(f"DELETE FROM {LEDGER} WHERE seq = ?", (row_id,))
        conn.commit()
    except sqlite3.Error as exc:
        conn.rollback()
        return {"ok": False, "applied": False, "dev_only": True,
                "error": f"sqlite refused the delete: {exc}"}
    finally:
        conn.close()

    return {
        "ok": True,
        "applied": True,
        "dev_only": True,
        "row_id": row_id,
        "deleted_row": original,
        "intent_seq": intent["seq"],
        "verify": verify(),
    }


def dev_restore() -> dict:
    """DEV-ONLY: put every dev-tampered row back exactly as it was.

    Restores the full row (all columns) from the audit_meta snapshot and then
    appends an honest "audit.tamper.restored" row, so the ledger ends up healthy
    again AND still carries the record that a demo happened.
    """
    if not dev_tamper_enabled():
        return _dev_disabled()
    conn = connect()
    restored: list[int] = []
    try:
        _ensure(conn)
        snaps = _snapshots(conn)
        if snaps:
            with _triggers_suspended(conn):
                for seq_str, row in sorted(snaps.items(), key=lambda kv: int(kv[0])):
                    seq = int(seq_str)
                    exists = conn.execute(
                        f"SELECT 1 FROM {LEDGER} WHERE seq = ?", (seq,)
                    ).fetchone()
                    if exists:
                        conn.execute(
                            f"""UPDATE {LEDGER} SET ts=?, actor=?, action=?, subject_type=?,
                                subject_id=?, payload_json=?, prev_hash=?, row_hash=?
                                WHERE seq=?""",
                            (row["ts"], row["actor"], row["action"], row["subject_type"],
                             row["subject_id"], row["payload_json"], row["prev_hash"],
                             row["row_hash"], seq),
                        )
                    else:
                        conn.execute(
                            f"""INSERT INTO {LEDGER}
                                (seq, ts, actor, action, subject_type, subject_id,
                                 payload_json, prev_hash, row_hash)
                                VALUES (?,?,?,?,?,?,?,?,?)""",
                            (seq, row["ts"], row["actor"], row["action"], row["subject_type"],
                             row["subject_id"], row["payload_json"], row["prev_hash"],
                             row["row_hash"]),
                        )
                    restored.append(seq)
            conn.execute("DELETE FROM audit_meta WHERE key = ?", (DEV_SNAPSHOT_KEY,))
            conn.commit()
    except sqlite3.Error as exc:
        conn.rollback()
        return {"ok": False, "dev_only": True, "error": f"sqlite refused the restore: {exc}",
                "verify": verify()}
    finally:
        conn.close()

    after = verify()
    if restored:
        record(
            DEV_ACTOR, "audit.tamper.restored", "audit_ledger", ",".join(str(s) for s in restored),
            {"dev_only": True, "restored_rows": restored,
             "note": "original rows restored from the audit_meta snapshot; chain re-verified",
             "verify_ok_after_restore": after["ok"]},
        )
        after = verify()
    return {"ok": after["ok"], "dev_only": True, "restored_rows": restored,
            "verify": after}


# --- L1: route-level audit decorator (appended Nov 22, 2026) ---
import functools as _functools
from flask import request as _flask_request


def audited(action, subject_type="route"):
    """Write one ledger row per HTTP request to a decorated view."""
    def deco(fn):
        @_functools.wraps(fn)
        def wrapper(*args, **kwargs):
            result = fn(*args, **kwargs)
            record(
                actor="http",
                action=action,
                subject_type=subject_type,
                subject_id=_flask_request.path,
                payload={
                    "method": _flask_request.method,
                    "status": getattr(result, "status_code", None),
                },
            )
            return result
        wrapper._audited_action = action
        return wrapper
    return deco


def _resolve_trace_id():
    """The active trace id, or None. Never raises — a broken context import
    must not take the ledger down."""
    try:
        from .context import current_trace_id
        return current_trace_id()
    except Exception:
        return None


def _merge_trace(payload, trace_id):
    """Merge trace_id into a dict payload; wrap None; leave anything else untouched."""
    if payload is None:
        return {"trace_id": trace_id}
    if isinstance(payload, dict):
        merged = dict(payload)
        merged.setdefault("trace_id", trace_id)
        return merged
    return payload
