"""LEGACY job-centric event log — now a PROJECTION of the audit layer.

Every row stores prev_hash (the hash of the previous row in the chain) and its
own hash, computed as:

    hash = sha256(prev_hash + "|" + canonical_json(row_without_hash))

so editing, deleting or reordering any row breaks verification from that point
on.

Status since the audit layer exists
-----------------------------------
``append_event`` is no longer called by any component. The single write path is
``orchestrator.audit.record(...)``, which appends the authoritative row to
``audit_ledger`` and then calls ``append_event`` itself (via ``legacy=...``) to
keep this table readable for every existing endpoint, page and API consumer.
Rows written to ``events`` before the audit layer existed were absorbed into
``audit_ledger`` once by ``audit.mirror_legacy_events()``, so no fact is lost
and no fact lives in two independent chains: this table is a derived view with a
compatibility schema, not a second source of truth.

Keeping the API is deliberate: ``/events``, ``/events/verify``,
``service.list_events`` and the job detail page all still work exactly as
before.
"""

from __future__ import annotations

import hashlib
import json
import sqlite3
from datetime import datetime, timezone

GENESIS = "0" * 64


def utcnow() -> str:
    return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"


def canonical(obj) -> str:
    return json.dumps(obj, sort_keys=True, separators=(",", ":"), default=str)


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


def head_hash(conn: sqlite3.Connection) -> str:
    row = conn.execute("SELECT hash FROM events ORDER BY id DESC LIMIT 1").fetchone()
    return row["hash"] if row else GENESIS


def append_event(
    conn: sqlite3.Connection,
    *,
    job_id: str | None,
    actor: str,
    kind: str,
    from_state: str | None,
    to_state: str | None,
    note: str = "",
    data: dict | None = None,
) -> dict:
    """Append one row to the LEGACY chain and return it. Caller owns the transaction.

    Do not call this from application code — go through ``audit.record(...,
    legacy={...})`` so the authoritative ledger row and this projection are
    written atomically by one write path. This function is kept public because
    it is the compatibility hook the audit layer itself uses, and because
    pre-existing callers/tests still append raw legacy rows.
    """
    prev = head_hash(conn)
    ts = utcnow()
    data_json = canonical(data) if data is not None else None
    body = {
        "ts": ts,
        "job_id": job_id,
        "actor": actor,
        "kind": kind,
        "from_state": from_state,
        "to_state": to_state,
        "note": note,
        "data": data_json,
        "prev_hash": prev,
    }
    h = compute_hash(prev, body)
    cur = conn.execute(
        """INSERT INTO events (ts, job_id, actor, kind, from_state, to_state, note, data, prev_hash, hash)
           VALUES (?,?,?,?,?,?,?,?,?,?)""",
        (ts, job_id, actor, kind, from_state, to_state, note, data_json, prev, h),
    )
    return {
        "id": cur.lastrowid,
        "ts": ts,
        "job_id": job_id,
        "actor": actor,
        "kind": kind,
        "from_state": from_state,
        "to_state": to_state,
        "note": note,
        "data": data,
        "prev_hash": prev,
        "hash": h,
    }


def row_to_event(row: sqlite3.Row) -> dict:
    d = dict(row)
    if d.get("data"):
        try:
            d["data"] = json.loads(d["data"])
        except (ValueError, TypeError):
            pass
    return d


def verify_chain(conn: sqlite3.Connection) -> dict:
    """Recompute the whole chain. Returns {ok, length, broken_at, reason}."""
    prev = GENESIS
    length = 0
    for row in conn.execute("SELECT * FROM events ORDER BY id ASC"):
        length += 1
        body = {
            "ts": row["ts"],
            "job_id": row["job_id"],
            "actor": row["actor"],
            "kind": row["kind"],
            "from_state": row["from_state"],
            "to_state": row["to_state"],
            "note": row["note"],
            "data": row["data"],
            "prev_hash": row["prev_hash"],
        }
        if row["prev_hash"] != prev:
            return {
                "ok": False,
                "length": length,
                "broken_at": row["id"],
                "reason": f"prev_hash mismatch at event {row['id']}",
            }
        expected = compute_hash(prev, body)
        if expected != row["hash"]:
            return {
                "ok": False,
                "length": length,
                "broken_at": row["id"],
                "reason": f"hash mismatch at event {row['id']} (row was modified)",
            }
        prev = row["hash"]
    return {"ok": True, "length": length, "broken_at": None, "reason": None, "head": prev}
