#!/usr/bin/env python3
"""Check an Everdeck audit log export: that its entries hang together as Everdeck wrote them, and, given an older
export of the same log that you kept, that nothing in the older one changed or vanished except what retention
removes.

    python3 verify-audit-export.py EXPORT [--previous OLDER_EXPORT] [--as-of 2026-12-01T00:00:00Z] [--list]

EXPORT is a file from the Audit log page's Export (CSV or JSON Lines; the script tells which). It needs Python 3.9
or later and nothing outside its standard library, so you can read every line of it first. It sends nothing
anywhere. It exits 0 when it found no problem, 1 when it found one, and 2 when it couldn't read a file.

What one file shows, and what it can't. Every entry's hash is recomputed and each entry's link to the one before
it is checked, so an entry edited in the file, or in Everdeck's database without its hash recomputed, shows. A
gap in a chain is a problem when the entry before it was younger than retention allows anything to be removed;
an older gap is noted. But someone able to recompute every hash after an entry they edited (only someone with
Everdeck's database could) leaves a file that hangs together: only an older export you kept shows that, with
--previous. Keep your exports.

How the log is chained (version 2, every entry written from Everdeck v0.28.0 on). Each log is a chain: an
account's own entries are one, and each company's entries another. Every entry has a `seq` in its chain (1, 2,
3, ...) and a hash:

    hash = SHA-256(previous entry's hash || row digest)       (nothing before the first entry, seq 1)
    row digest = SHA-256("everdeck.audit.v2" || d(account_id) || d(company_id) || d(seq) || d(at)
                         || d(actor_kind) || d(actor_id) || d(actor_label) || d(actor_shape) || d(action)
                         || d(target) || d(detail) || d(ip) || d(role))
    d(field) = SHA-256(salt || name || 0x00 || value)          value: 0x00 when empty (null),
                                                               else 0x01 and its UTF-8 text

`at` is the entry's time in UTC, `2026-11-24T09:30:00.000000Z`; `target` and `detail` are the text Everdeck
stored, which the export gives exactly; `actor_shape` records the JSON types of the actor's kind, id and label
(always strings) and that it has no other keys. Four fields an export may hide: the actor's id (Everdeck staff
are never named), the detail (secret hints, unless you manage those secrets), the IP address (company logs
don't show one) and the actor's account role (never shown). Each of those has a salt of its own, derived from a
random salt kept with the entry: salt = SHA-256(entry salt || name). For a field it shows, the export gives that
salt, so the field can be checked; for a field it hides, it gives the field's digest instead, which can't be
guessed without the salt. Either way the entry's hash covers every field, so a change to a hidden field shows
too. The other fields have no salt (an empty one); the kind, name and shape of the actor may also be given as a
digest when the page shows them in another form. An entry's id and its company's name aren't covered.

Entries written before v0.28.0 (version 1) have a hash Everdeck checks on its side, but it was made from text
that depended on the database session's settings, so it can't be recomputed from an export: they are listed
as entries this script couldn't check, never as problems on their own.

Every entry's chain object also gives the log the export is of (`log`: the account's own, or a company's, with
its id), the times it covers (`range`, from and to) and when it was made (`exported_at`). A gap is judged by
the entry's age when the file was made (never later than when you run the script), whatever times it covers. In
an export of the account's own log, a company's entries are only those Everdeck staff made, so gaps between them
say nothing. Every export from v0.28.0 on says which log it is on every entry: an entry that doesn't is a problem.
Whether an entry is Everdeck staff's is read from what its hash covers: when the kind of actor is given as a
digest, the entry is staff's only if that digest is the one of "staff". With --previous, entries in both files must have the same hash (and, for version 1 entries, the
same value in every field both files show), and an entry of the older file that the newer one covers (a time
inside its range, or a seq inside the seqs it holds of that chain) must still be there, unless it is older than
the shortest time Everdeck may keep it: 90 days for a company's entries (a company may keep them for 90 days to 7
years), a year for the account's own entries and for entries by Everdeck staff. Ages are counted to when the
newer file was made, or to --as-of when that is earlier. Two files of different logs aren't compared.
"""

from __future__ import annotations

import argparse
import csv
import hashlib
import io
import itertools
import json
import re
import sys
from collections.abc import Iterable, Sequence
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone

VERSION = 2
DOMAIN = b"everdeck.audit.v2"
# The row digest's fields, in order.
FIELDS = (
    "account_id",
    "company_id",
    "seq",
    "at",
    "actor_kind",
    "actor_id",
    "actor_label",
    "actor_shape",
    "action",
    "target",
    "detail",
    "ip",
    "role",
)
# The fields an export may hide, each salted.
SALTED = frozenset({"actor_id", "detail", "ip", "role"})
# The fields an export may give a digest of instead of showing: the salted four, and the actor's kind, name and
# shape when the page shows them in another form. A digest of any other field is a problem.
HIDEABLE = SALTED | {"actor_kind", "actor_label", "actor_shape"}
# What every actor Everdeck writes looks like to the hash (audit_chain_actor_shape in the database).
STANDARD_SHAPE = '{"id": "string", "kind": "string", "rest": {}, "label": "string"}'
FIELD_WORDS = {
    "actor_kind": "the kind of actor",
    "actor_id": "the actor's id",
    "actor_label": "the actor's name",
    "actor_shape": "the actor's other keys",
    "detail": "the detail",
    "ip": "the IP address",
    "role": "the actor's account role",
}
# The shortest time Everdeck keeps an entry (legal/data-retention.md): a company's own period is 90 days to 7
# years, and entries by Everdeck staff, the account's own entries, and entries by the account's owners and admins
# are kept at least a year. An export hides the role, so a company's entries count 90 days unless staff wrote them.
COMPANY_FLOOR = timedelta(days=90)
YEAR_FLOOR = timedelta(days=365)
# The digest of the kind of actor Everdeck staff are (an unsalted field).
STAFF_KIND_DIGEST = hashlib.sha256(b"actor_kind\x00\x01staff").hexdigest()
# A CSV cell a spreadsheet would read as a formula is written with an apostrophe in front of it.
FORMULA_STARTS = ("=", "+", "-", "@", "\t", "\r")
CSV_COLUMNS = (
    "id",
    "at",
    "action",
    "actor_kind",
    "actor_id",
    "actor_label",
    "company_id",
    "company_name",
    "target",
    "detail",
    "ip",
    "account_id",
    "chain",
)
# The fields a version 1 entry is compared on between two files, where neither hides it.
SHOWN_FIELDS = (
    "at",
    "action",
    "actor_kind",
    "actor_id",
    "actor_label",
    "company_id",
    "target",
    "detail",
    "ip",
)
_UTC = timezone(timedelta(0))
# The most ways to read one entry's CSV cells (each apostrophe may be the export's or the value's own).
_MAX_READINGS = 64
# A detail may be long; a CSV cell is read whole up to this many characters.
_CELL_MAX = 256 * 1024 * 1024
_ID = re.compile(r"[0-9]{1,19}")
_UUID = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
_HEX = re.compile(r"[0-9a-f]{64}")
# How many entries a line lists before it says how many more there are.
_LISTED = 50


# -- the hash ---------------------------------------------------------------------------------------------------


def encode(value: str | None) -> bytes:
    """A field's value as the digest reads it: 0x00 for none, else 0x01 and its UTF-8 bytes."""
    return b"\x00" if value is None else b"\x01" + value.encode("utf-8")


def field_salt(entry_salt: bytes, name: str) -> bytes:
    """The salt of one hidden-or-shown field, derived from the entry's own random salt."""
    return hashlib.sha256(entry_salt + name.encode("utf-8")).digest()


def field_digest(name: str, value: str | None, salt: bytes = b"") -> bytes:
    return hashlib.sha256(salt + name.encode("utf-8") + b"\x00" + encode(value)).digest()


def row_digest(digests: dict[str, bytes]) -> bytes:
    return hashlib.sha256(DOMAIN + b"".join(digests[name] for name in FIELDS)).digest()


def chain_hash(prev_hash: bytes | None, row: bytes) -> bytes:
    return hashlib.sha256((prev_hash or b"") + row).digest()


def utc_text(at: datetime) -> str:
    """An entry's time as the hash reads it, from any time with an offset."""
    when = at.astimezone(_UTC)
    return (
        f"{when.year:04d}-{when.month:02d}-{when.day:02d}T{when.hour:02d}:{when.minute:02d}:{when.second:02d}"
        f".{when.microsecond:06d}Z"
    )


def digests_of(values: dict[str, str | None], entry_salt: bytes) -> dict[str, bytes]:
    """Every field's digest from its value and the entry's salt (what Everdeck does when it writes an entry)."""
    return {
        name: field_digest(name, values[name], field_salt(entry_salt, name) if name in SALTED else b"")
        for name in FIELDS
    }


def entry_hash(prev_hash: bytes | None, values: dict[str, str | None], entry_salt: bytes) -> bytes:
    return chain_hash(prev_hash, row_digest(digests_of(values, entry_salt)))


def disclose(
    values: dict[str, str | None], entry_salt: bytes, hidden: Iterable[str]
) -> dict[str, dict[str, str]]:
    """What an export gives about an entry's fields: the salt of each salted field it shows, and the digest of
    each field it hides (`hidden`, salted or not)."""
    hide = set(hidden)
    salts = {
        name: field_salt(entry_salt, name).hex() for name in FIELDS if name in SALTED and name not in hide
    }
    digests = {name: digest.hex() for name, digest in digests_of(values, entry_salt).items() if name in hide}
    return {"salts": salts, "digests": digests}


# -- reading an export ------------------------------------------------------------------------------------------


class ExportError(Exception):
    """A file that isn't an export this script can read."""


def safe(text: object) -> str:
    """Text from a file as it is safe to print: every character that isn't printable (a control character, a line
    separator) written as its escape, so nothing in a file can move the cursor or forge a line of this report."""
    return "".join(ch if ch.isprintable() else f"\\u{ord(ch):04x}" for ch in str(text))


@dataclass
class Entry:
    """One entry of an export: where it is, what it shows, and its chain object."""

    line: int
    id: str
    account_id: str
    company_id: str | None
    at: datetime
    action: str
    actor_kind: str
    staff: bool
    version: int
    seq: int | None
    prev_hash: str | None
    hash: str
    # Each field the hash reads, as every way the file can be read (a CSV cell's leading apostrophe may be the
    # export's own), and what the chain object gives: salts of shown fields, digests of hidden ones.
    readings: dict[str, list[str | None]]
    salts: dict[str, str]
    digests: dict[str, str]
    # The times the export covers, [from, to), and when it was made, when it says.
    span: tuple[datetime, datetime] | None = None
    exported_at: datetime | None = None
    # The fields a version 1 entry's file doesn't show as stored (its chain object's "hidden").
    hidden: frozenset[str] = frozenset()
    # The log the file says it is of: "account", "company <id>", or None when it doesn't say.
    log: str | None = None

    @property
    def chain(self) -> tuple[str, str | None]:
        return (self.account_id, self.company_id)

    def where(self) -> str:
        log = f"company {self.company_id}'s log" if self.company_id else "the account's own log"
        place = f"seq {self.seq} of {log}" if self.seq is not None else log
        return f"entry {self.id} ({place}, {utc_text(self.at)})"


@dataclass
class Export:
    path: str
    kind: str  # "CSV" or "JSON Lines"
    entries: list[Entry]

    @property
    def account_id(self) -> str | None:
        found = {entry.account_id for entry in self.entries}
        return found.pop() if len(found) == 1 else None

    @property
    def exported_at(self) -> datetime | None:
        """When the file was made, as its entries say."""
        found = [entry.exported_at for entry in self.entries if entry.exported_at is not None]
        return max(found) if found else None

    @property
    def span(self) -> tuple[datetime, datetime] | None:
        found = [entry.span for entry in self.entries if entry.span is not None]
        if not found:
            return None
        return min(s[0] for s in found), max(s[1] for s in found)

    def made(self, now: datetime) -> datetime:
        """The file's time, for ages: when it was made, never later than `now`. Retention runs on the day, not on
        the times a file covers, so an entry's age is counted to the day the file was made, however long ago the
        range it covers ended."""
        if self.exported_at is not None:
            return min(now, self.exported_at)
        return now

    def declared(self) -> set[str | None]:
        """The logs the entries say the file is of (None for an entry that doesn't say)."""
        return {entry.log for entry in self.entries}

    def log(self) -> str:
        """Which log the file is of: the one every entry names (`log` in its chain object), else "unknown". A file
        that doesn't say, or says more than one, is "unknown", and its companies' chains are read as fragments."""
        declared = self.declared()
        if len(declared) == 1:
            only = next(iter(declared))
            if only is not None:
                return only
        return "unknown"

    def inferred(self) -> str:
        """Which log the file looks like, from its entries alone: "account", "company <id>", or "unknown" (only
        Everdeck staff entries about one company, which both logs hold)."""
        companies = {entry.company_id for entry in self.entries}
        if None in companies or len(companies) > 1:
            return "account"
        if not companies:
            return "unknown"
        if any(not entry.staff for entry in self.entries):
            return f"company {next(iter(companies))}"
        return "unknown"


def _when(text: str, where: str) -> datetime:
    try:
        at = datetime.fromisoformat(text.strip().replace("Z", "+00:00"))
    except ValueError:
        raise ExportError(f"{where}: its time {safe(text)!r} isn't a date and time") from None
    if at.tzinfo is None:
        raise ExportError(f"{where}: its time {safe(text)!r} has no offset from UTC")
    return at


def _text(value: object, where: str, what: str, *, empty: bool = True) -> str:
    if not isinstance(value, str) or (not empty and not value):
        raise ExportError(f"{where}: its {what} isn't text")
    return value


def _text_or_none(value: object, where: str, what: str) -> str | None:
    if value is None:
        return None
    return _text(value, where, what)


def _hex_text(value: object, where: str, what: str) -> str:
    if not isinstance(value, str) or not _HEX.fullmatch(value):
        raise ExportError(f"{where}: its {what} isn't a SHA-256 in hex")
    return value


def _chain_object(value: object, where: str) -> dict:
    if isinstance(value, str):
        try:
            value = json.loads(value)
        except ValueError:
            raise ExportError(f"{where}: its chain isn't JSON") from None
    if not isinstance(value, dict) or value.get("v") not in (1, 2) or not isinstance(value.get("hash"), str):
        raise ExportError(
            f"{where}: it has no chain object; was the file made before Everdeck v0.28.0, or changed?"
        )
    return value


def _entry(line: int, row: dict, readings: dict[str, list[str | None]], chain: dict) -> Entry:
    """One entry from its shown fields (`row`: id, account_id, company_id, at, action, actor_kind as text), the
    ways the file can be read, and its chain object, every part checked for its type and form."""
    where = f"line {line}"
    version = chain["v"]
    seq = chain.get("seq")
    if version == VERSION and (not isinstance(seq, int) or isinstance(seq, bool) or seq < 1):
        raise ExportError(f"{where}: its chain has no seq")
    salts = chain.get("salts") or {}
    digests = chain.get("digests") or {}
    if not isinstance(salts, dict) or not isinstance(digests, dict):
        raise ExportError(f"{where}: its chain's salts or digests aren't objects")
    entry_id = _text(row.get("id"), where, "id")
    if not _ID.fullmatch(entry_id):
        raise ExportError(f"{where}: its id {safe(entry_id)!r} isn't a number")
    account = _text(row.get("account_id"), where, "account_id")
    if not _UUID.fullmatch(account):
        raise ExportError(f"{where}: its account_id {safe(account)!r} isn't an id")
    company = _text_or_none(row.get("company_id"), where, "company id") or None
    if company is not None and not _UUID.fullmatch(company):
        raise ExportError(f"{where}: its company id {safe(company)!r} isn't an id")
    span = None
    covers = chain.get("range")
    if covers is not None:
        if not isinstance(covers, list) or len(covers) != 2 or not all(isinstance(c, str) for c in covers):
            raise ExportError(f"{where}: its chain's range isn't two times")
        span = (_when(covers[0], f"{where}: its range"), _when(covers[1], f"{where}: its range"))
    made = chain.get("exported_at")
    exported_at = (
        _when(_text(made, where, "export time"), f"{where}: its export time") if made is not None else None
    )
    hidden = chain.get("hidden") or []
    if not isinstance(hidden, list) or not all(isinstance(h, str) for h in hidden):
        raise ExportError(f"{where}: its chain's hidden fields aren't a list of names")
    log = _log_of(chain.get("log"), where)
    prev = chain.get("prev_hash")
    return Entry(
        line=line,
        id=entry_id,
        account_id=account,
        company_id=company,
        at=_when(_text(row.get("at"), where, "time", empty=False), where),
        action=_text(row.get("action"), where, "action"),
        actor_kind=_text(row.get("actor_kind"), where, "actor's kind"),
        staff=_staff(row.get("actor_kind"), digests),
        version=version,
        seq=seq if version == VERSION else None,
        prev_hash=_hex_text(prev, where, "previous hash") if prev is not None else None,
        hash=_hex_text(chain["hash"], where, "hash"),
        readings=readings,
        salts={_text(k, where, "salt's name"): _hex_text(v, where, "salt") for k, v in salts.items()},
        digests={_text(k, where, "digest's name"): _hex_text(v, where, "digest") for k, v in digests.items()},
        span=span,
        exported_at=exported_at,
        hidden=frozenset(hidden),
        log=log,
    )


def _staff(shown: object, digests: object) -> bool:
    """Whether an entry is Everdeck staff's, as its hash has it: when the file gives the kind of actor as a digest,
    by that digest (a kind shown as "staff" over another kind's digest still checks, and isn't staff's)."""
    if isinstance(digests, dict) and "actor_kind" in digests:
        return digests["actor_kind"] == STAFF_KIND_DIGEST
    return shown == "staff"


def _log_of(value: object, where: str) -> str | None:
    """A chain object's `log`: {"kind": "account"} or {"kind": "company", "id": <the company's id>}."""
    if value is None:
        return None
    if isinstance(value, dict) and value.get("kind") == "account" and set(value) == {"kind"}:
        return "account"
    if isinstance(value, dict) and value.get("kind") == "company" and set(value) == {"kind", "id"}:
        company = value.get("id")
        if isinstance(company, str) and _UUID.fullmatch(company):
            return f"company {company}"
    raise ExportError(f"{where}: its chain's log isn't the account's own or a company's")


def _readings_jsonl(row: dict, where: str) -> dict[str, list[str | None]]:
    actor = row.get("actor")
    company = row.get("company")
    if not isinstance(actor, dict):
        raise ExportError(f"{where}: its actor isn't an object")
    if company is not None and not isinstance(company, dict):
        raise ExportError(f"{where}: its company isn't an object")
    values: dict[str, str | None] = {
        "account_id": _text_or_none(row.get("account_id"), where, "account_id"),
        "company_id": _text_or_none(company.get("id"), where, "company id") if company else None,
        "action": _text_or_none(row.get("action"), where, "action"),
        "actor_kind": _text_or_none(actor.get("kind"), where, "actor's kind"),
        "actor_id": _text_or_none(actor.get("id"), where, "actor's id"),
        "actor_label": _text_or_none(actor.get("label"), where, "actor's name"),
        "target": _text_or_none(row.get("target"), where, "target"),
        "detail": _text_or_none(row.get("detail"), where, "detail"),
        "ip": _text_or_none(row.get("ip"), where, "IP address"),
    }
    return {name: [value] for name, value in values.items()}


def _cell_readings(cell: str) -> list[str]:
    """Every value a CSV cell can hold: with an apostrophe before a formula character, the export may have
    added it, or the value may start with it."""
    if len(cell) > 1 and cell[0] == "'" and cell[1] in FORMULA_STARTS:
        return [cell[1:], cell]
    return [cell]


def _readings_csv(row: dict) -> dict[str, list[str | None]]:
    out: dict[str, list[str | None]] = {}
    for name in (
        "account_id",
        "company_id",
        "action",
        "actor_kind",
        "actor_id",
        "actor_label",
        "target",
        "detail",
    ):
        cell = row.get(name) or ""
        if name in ("company_id", "actor_id") and cell == "":
            out[name] = [None]  # an empty cell is a value the export doesn't have
        else:
            out[name] = list(_cell_readings(cell))
    cell = row.get("ip") or ""
    out["ip"] = [None] if cell == "" else list(_cell_readings(cell))
    return out


def read_export(path: str) -> Export:
    """An export file, either format."""
    try:
        with open(path, encoding="utf-8-sig", newline="") as handle:
            text = handle.read()
    except OSError as err:
        raise ExportError(f"{safe(path)}: {safe(err.strerror or err)}") from None
    except UnicodeDecodeError:
        raise ExportError(f"{safe(path)}: isn't UTF-8 text") from None
    if text.startswith("id,"):
        return Export(path, "CSV", list(_read_csv(text)))
    return Export(path, "JSON Lines", list(_read_jsonl(text)))


def _read_csv(text: str) -> Iterable[Entry]:
    csv.field_size_limit(_CELL_MAX)
    reader = csv.DictReader(io.StringIO(text, newline=""))
    missing = [column for column in CSV_COLUMNS if column not in (reader.fieldnames or [])]
    if missing:
        raise ExportError(f"the CSV has no {', '.join(missing)} column; was it made before Everdeck v0.28.0?")
    for row in reader:
        number = reader.line_num
        if None in row or any(value is None for value in row.values()):
            raise ExportError(f"line {number} doesn't have the CSV's {len(CSV_COLUMNS)} columns")
        chain = _chain_object(row.get("chain") or "", f"line {number}")
        cells = {name: (row.get(name) or "") for name in CSV_COLUMNS}
        shown = {
            "id": cells["id"],
            "account_id": cells["account_id"],
            "company_id": cells["company_id"] or None,
            "at": cells["at"],
            "action": _cell_readings(cells["action"])[0],
            "actor_kind": _cell_readings(cells["actor_kind"])[0],
        }
        yield _entry(number, shown, _readings_csv(row), chain)


def _read_jsonl(text: str) -> Iterable[Entry]:
    # Split on newlines only: str.splitlines would also split inside a value holding U+2028 or the like, which
    # the file writes as it is.
    for number, line in enumerate(text.split("\n"), start=1):
        if not line.strip():
            continue
        where = f"line {number}"
        try:
            row = json.loads(line)
        except ValueError:
            raise ExportError(f"{where} isn't JSON: is this a CSV or JSON Lines export?") from None
        except RecursionError:
            raise ExportError(f"{where} nests deeper than an export does") from None
        if not isinstance(row, dict):
            raise ExportError(f"{where} isn't an entry")
        actor = row.get("actor")
        company = row.get("company")
        readings = _readings_jsonl(row, where)
        shown = {
            "id": row.get("id"),
            "account_id": row.get("account_id"),
            "company_id": company.get("id") if isinstance(company, dict) else None,
            "at": row.get("at"),
            "action": row.get("action"),
            "actor_kind": actor.get("kind") if isinstance(actor, dict) else None,
        }
        yield _entry(number, shown, readings, _chain_object(row.get("chain"), where))


# -- checking one export ----------------------------------------------------------------------------------------


@dataclass
class Report:
    """What the checks found. `problems` make the run fail; `unchecked` and `notes` don't."""

    problems: list[str] = field(default_factory=list)
    unchecked: list[str] = field(default_factory=list)
    notes: list[str] = field(default_factory=list)
    checked: int = 0
    linked: int = 0
    v1: list[Entry] = field(default_factory=list)
    hidden: dict[str, list[Entry]] = field(default_factory=dict)


def _bytes(value: str | None) -> bytes | None:
    return bytes.fromhex(value) if value is not None else None


def hash_holds(entry: Entry) -> bool:
    """Whether a version 2 entry's fields, as the file shows them (or their digests, for those it hides), give
    the hash it carries. Digests of fields an export never hides don't count: such an entry doesn't hold."""
    if set(entry.digests) - HIDEABLE:
        return False
    readings = {
        **entry.readings,
        "seq": [str(entry.seq)],
        "at": [utc_text(entry.at)],
        "actor_shape": [STANDARD_SHAPE],
        "role": [None],
    }
    given = {name: bytes.fromhex(digest) for name, digest in entry.digests.items()}
    for name in SALTED:
        if name not in given and name not in entry.salts:
            return False
    salts = {name: bytes.fromhex(value) for name, value in entry.salts.items()}
    expected = bytes.fromhex(entry.hash)
    prev = _bytes(entry.prev_hash)
    open_names = [name for name in FIELDS if name not in given]
    choices = [readings.get(name, [None]) for name in open_names]
    for n, combination in enumerate(itertools.product(*choices)):
        if n >= _MAX_READINGS:
            break
        digests = dict(given)
        for i, name in enumerate(open_names):
            digests[name] = field_digest(
                name, combination[i], salts.get(name, b"") if name in SALTED else b""
            )
        if chain_hash(prev, row_digest(digests)) == expected:
            return True
    return False


def _group(entries: Iterable[Entry]) -> dict[tuple[str, str | None], list[Entry]]:
    chains: dict[tuple[str, str | None], list[Entry]] = {}
    for entry in entries:
        chains.setdefault(entry.chain, []).append(entry)
    return chains


def _log_name(chain: tuple[str, str | None]) -> str:
    return f"company {chain[1]}'s log" if chain[1] else "the account's own log"


def log_floor(chain: tuple[str, str | None]) -> timedelta:
    """The shortest time Everdeck keeps any entry of a log: a year for the account's own, 90 days for a company's."""
    return COMPANY_FLOOR if chain[1] else YEAR_FLOOR


def check(export: Export, *, now: datetime | None = None) -> Report:
    """Every version 2 entry's hash, the links, order and gaps of each chain's entries in the file, what the file
    is made of, and where version 1 entries sit."""
    report = Report()
    made = export.made(now or datetime.now(_UTC))
    _check_mix(report, export)
    # A company's chain holds only Everdeck staff's entries in the account's own log, and may in a file that
    # doesn't say which log it is: its gaps say nothing there.
    fragments = not export.log().startswith("company ")
    current = [entry for entry in export.entries if entry.version == VERSION]
    report.v1 = [entry for entry in export.entries if entry.version != VERSION]
    for entry in current:
        unknown = sorted(set(entry.digests) - HIDEABLE)
        if unknown:
            report.problems.append(
                f"{entry.where()} gives a digest in place of {', '.join(safe(name) for name in unknown)}, which an "
                "export never hides: what it shows there can't be confirmed."
            )
        elif hash_holds(entry):
            report.checked += 1
        else:
            report.problems.append(
                f"{entry.where()} doesn't match its hash: something in it changed after it was written."
            )
        for name in entry.digests:
            report.hidden.setdefault(name, []).append(entry)
        for name in ("actor_id", "ip"):
            if name in entry.digests and any(
                value not in (None, "") for value in entry.readings.get(name, [None])
            ):
                report.problems.append(
                    f"{entry.where()} shows {FIELD_WORDS[name]}, which the export says it hides: that value isn't "
                    "what Everdeck stored."
                )
    for chain, entries in sorted(_group(current).items(), key=lambda item: (item[0][1] or "", item[0][0])):
        entries.sort(key=lambda entry: entry.seq or 0)
        _check_chain(report, chain, entries, fragments=fragments and chain[1] is not None, made=made)
    _check_v1(report, current)
    if report.v1:
        report.unchecked.append(
            f"{len(report.v1):,} {'entry was' if len(report.v1) == 1 else 'entries were'} written before Everdeck "
            "v0.28.0 (version 1). Their hashes were made from text that depended on the database session, so "
            "they can't be recomputed from an export; Everdeck checks them on its side, and --previous compares "
            "every field two exports both show."
        )
    report.unchecked.append(
        "The hash doesn't cover an entry's id or its company's name, so those can't be confirmed from the file."
    )
    return report


def _check_mix(report: Report, export: Export) -> None:
    """A file holds one account's log: its own entries with Everdeck staff's entries about its companies, or one
    company's entries."""
    accounts = {entry.account_id for entry in export.entries}
    if len(accounts) > 1:
        report.problems.append(
            f"The file mixes entries of {len(accounts)} accounts; an export holds one account's log."
        )
    companies = {entry.company_id for entry in export.entries if entry.company_id and not entry.staff}
    own = any(entry.company_id is None for entry in export.entries)
    declared = export.declared()
    if len(companies) > 1 or (companies and own) or len(declared - {None}) > 1:
        report.problems.append(
            "The file mixes entries of more than one log: an export holds one company's entries, or the "
            "account's own with Everdeck staff's entries about its companies."
        )
    unsaid = [entry for entry in export.entries if entry.log is None]
    if unsaid:
        report.problems.append(
            f"{len(unsaid):,} {'entry doesn' if len(unsaid) == 1 else 'entries don'}'t say which log the file "
            f"holds (entries {', '.join(entry.id for entry in unsaid[:_LISTED])}"
            f"{' and more' if len(unsaid) > _LISTED else ''}): every export from Everdeck v0.28.0 on does, so the "
            "file was changed, and its gaps can't be judged."
        )
    for entry in export.entries:
        if entry.log is None:
            continue
        outside = (
            entry.company_id != entry.log.removeprefix("company ")
            if entry.log.startswith("company ")
            else entry.company_id is not None and not entry.staff
        )
        if outside:
            report.problems.append(
                f"{entry.where()} isn't an entry of the log its file says it holds: entries were mixed in."
            )


def _check_chain(
    report: Report,
    chain: tuple[str, str | None],
    entries: list[Entry],
    *,
    fragments: bool,
    made: datetime,
) -> None:
    """One chain's entries in the file, in seq order. `fragments`: a company's chain in an account log's file,
    which holds only its Everdeck staff entries, so gaps say nothing. A gap after an entry younger than the log's
    floor when the file was made (`made`) is a problem: retention can't have made it."""
    log = _log_name(chain)
    floor = log_floor(chain)
    gaps = 0
    missing = 0
    for i, after in enumerate(entries):
        seq = after.seq or 0
        if seq == 1 and after.prev_hash is not None:
            report.problems.append(f"{after.where()} is its chain's first entry but names a previous one.")
        if seq > 1 and after.prev_hash is None:
            report.problems.append(
                f"{after.where()} comes after its chain's first entry but names no previous one."
            )
        if i == 0:
            continue
        before = entries[i - 1]
        before_seq = before.seq or 0
        if seq == before_seq:
            report.problems.append(
                f"{after.where()} has the same seq as entry {before.id}: the chain was forked or an entry copied."
            )
            continue
        if after.at < before.at:
            report.problems.append(
                f"{after.where()} is dated before entry {before.id}, which comes before it in its chain: "
                "the entries were reordered."
            )
        if seq == before_seq + 1:
            if after.prev_hash != before.hash:
                report.problems.append(
                    f"{after.where()} doesn't link to entry {before.id} before it: one of them was replaced, "
                    "or an entry was put between them."
                )
            else:
                report.linked += 1
        elif not fragments:
            gap = seq - before_seq - 1
            age = made - before.at
            if age < floor:
                report.problems.append(
                    f"{gap:,} {'entry' if gap == 1 else 'entries'} of {log} (seqs {before_seq + 1} to {seq - 1}) "
                    f"{'is' if gap == 1 else 'are'} missing after {before.where()}, which was only {age.days} days "
                    f"old when the file was made: retention never removes an entry of this log younger than "
                    f"{floor.days} days, so they were removed or the file was cut."
                )
            else:
                gaps += 1
                missing += gap
    if gaps:
        report.notes.append(
            f"{missing:,} {'entry' if missing == 1 else 'entries'} of {log} in {gaps:,} "
            f"{'gap' if gaps == 1 else 'gaps'} {'is' if missing == 1 else 'are'} not in this file, each after an "
            "entry old enough for retention to have removed them. The links across those gaps can't be checked "
            "from this file; --previous with an older export checks that nothing went that shouldn't."
        )


def _check_v1(report: Report, current: list[Entry]) -> None:
    """Version 1 entries came before every version 2 one: an entry that says it is version 1 but sits after them
    (a later id, or a later time in the same account) was made to look like one, which would hide an edit."""
    if not current:
        return
    first_id = min(int(entry.id) for entry in current)
    first_at: dict[str, datetime] = {}
    for entry in current:
        first_at[entry.account_id] = min(first_at.get(entry.account_id, entry.at), entry.at)
    for entry in report.v1:
        later_at = entry.account_id in first_at and entry.at > first_at[entry.account_id]
        if int(entry.id) > first_id or later_at:
            report.problems.append(
                f"{entry.where()} says it was written before v0.28.0 (version 1), but it comes after entries "
                "written since: an entry made to look older can't be checked, which would hide an edit."
            )


# -- comparing with an older export -----------------------------------------------------------------------------


def floor_of(entry: Entry) -> timedelta:
    """The shortest time Everdeck keeps `entry` (COMPANY_FLOOR, YEAR_FLOOR)."""
    if entry.company_id is None or entry.staff:
        return YEAR_FLOOR
    return COMPANY_FLOOR


def _place(entry: Entry) -> int:
    """Where an entry sits: its seq in its chain, or, written before v0.28.0, its id (ids increase over time)."""
    if entry.version == VERSION and entry.seq is not None:
        return entry.seq
    return int(entry.id)


def _same_shown(older: Entry, newer: Entry) -> list[str]:
    """The fields two files both show of a version 1 entry that differ between them."""
    differ = []
    for name in SHOWN_FIELDS:
        if name in older.hidden or name in newer.hidden:
            continue
        if name == "at":
            if older.at != newer.at:
                differ.append(name)
            continue
        if name == "action":
            if older.action != newer.action:
                differ.append(name)
            continue
        if not set(older.readings.get(name, [None])) & set(newer.readings.get(name, [None])):
            differ.append(name)
    return differ


def compare(older: Export, newer: Export, *, as_of: datetime) -> Report:
    """What became of the older file's entries in the newer one, ages counted to `as_of`."""
    report = Report()
    if older.account_id and newer.account_id and older.account_id != newer.account_id:
        raise ExportError("the two files are exports of different accounts")
    logs = {f.log() if f.log() != "unknown" else f.inferred() for f in (older, newer)} - {"unknown"}
    if len(logs) > 1:
        raise ExportError("the two files are exports of different logs; compare exports of the same log")
    if not newer.entries:
        report.notes.append("The newer file has no entries, so nothing of the older one could be compared.")
        return report
    span = newer.span
    if span is not None:
        first, last, inclusive = span[0], span[1], False
    else:
        first = min(entry.at for entry in newer.entries)
        last, inclusive = max(entry.at for entry in newer.entries), True

    def key(entry: Entry) -> tuple:
        return (*entry.chain, entry.seq) if entry.version == VERSION else ("v1", entry.id)

    def seqs(entries: Sequence[Entry]) -> dict[tuple, tuple[int, int]]:
        found: dict[tuple, tuple[int, int]] = {}
        for entry in entries:
            group = (entry.version, *entry.chain)
            place = _place(entry)
            low, high = found.get(group, (place, place))
            found[group] = (min(low, place), max(high, place))
        return found

    new_by_key = {key(entry): entry for entry in newer.entries}
    old_by_key = {key(entry): entry for entry in older.entries}
    new_span, old_span = seqs(newer.entries), seqs(older.entries)
    same = past_floor = outside = 0
    for entry in older.entries:
        found = new_by_key.get(key(entry))
        if found is not None:
            if found.hash != entry.hash or found.prev_hash != entry.prev_hash:
                report.problems.append(
                    f"{entry.where()} has a different hash in the newer file: it changed between the exports."
                )
            elif entry.version != VERSION and _same_shown(entry, found):
                report.problems.append(
                    f"{entry.where()} shows a different {', '.join(_same_shown(entry, found))} in the newer file: "
                    "it changed between the exports."
                )
            else:
                same += 1
            continue
        place = _place(entry)
        low, high = new_span.get((entry.version, *entry.chain), (0, -1))
        in_time = first <= entry.at < last or (inclusive and entry.at == last)
        if not (low <= place <= high or in_time):
            outside += 1
            continue
        age = as_of - entry.at
        if age > floor_of(entry):
            past_floor += 1
        else:
            report.problems.append(
                f"{entry.where()} is in the older file but not the newer one, and was only {age.days} days old "
                "when the newer file was made: retention doesn't remove an entry that soon."
            )
    for entry in newer.entries:
        if key(entry) in old_by_key:
            continue
        place = _place(entry)
        low, high = old_span.get((entry.version, *entry.chain), (0, -1))
        if low < place < high:
            report.problems.append(
                f"{entry.where()} is in the newer file but not the older one, though it falls between entries "
                "the older one holds: it was added afterwards, or left out of the older file."
            )
    report.notes.append(
        f"{same:,} {'entry is' if same == 1 else 'entries are'} in both files with the same hash and links."
    )
    if past_floor:
        report.notes.append(
            f"{past_floor:,} {'entry' if past_floor == 1 else 'entries'} of the older file "
            f"{'is' if past_floor == 1 else 'are'} gone, each older than the shortest time Everdeck keeps it, "
            "as retention removes them."
        )
    if outside:
        report.notes.append(
            f"{outside:,} {'entry' if outside == 1 else 'entries'} of the older file "
            f"{'is' if outside == 1 else 'are'} outside what the newer file covers, so not compared."
        )
    return report


# -- the command ------------------------------------------------------------------------------------------------


def _describe(export: Export) -> str:
    chains = len(_group(export.entries))
    count = len(export.entries)
    account = export.account_id or "several accounts"
    return (
        f"{safe(export.path)}: {export.kind}, account {account}, {count:,} {'entry' if count == 1 else 'entries'} "
        f"in {chains:,} {'chain' if chains == 1 else 'chains'}."
    )


def _ids(entries: Sequence[Entry], *, listing: bool) -> str:
    ids = [entry.id for entry in entries]
    if listing or len(ids) <= _LISTED:
        return ", ".join(ids)
    return f"{', '.join(ids[:_LISTED])} and {len(ids) - _LISTED:,} more (--list shows them all)"


def _hidden_lines(report: Report, *, listing: bool) -> list[str]:
    lines = []
    for name in FIELDS:
        entries = report.hidden.get(name)
        if not entries or name == "role":
            continue
        if name == "detail":
            lines.append(
                f"{len(entries):,} {'entry shows a detail' if len(entries) == 1 else 'entries show a detail'} with "
                "secret hints left out (they show only for people who manage those secrets). That text isn't "
                "what Everdeck stored, so it can't be confirmed; each entry's hash still covers what was stored: "
                f"entries {_ids(entries, listing=listing)}."
            )
            continue
        why = {
            "actor_id": "Everdeck staff aren't named",
            "ip": "this log doesn't show addresses, or Everdeck staff made the entry",
        }.get(name, "the export shows it in another form")
        ids = f": entries {_ids(entries, listing=True)}" if listing else ""
        lines.append(
            f"{len(entries):,} {'entry hides' if len(entries) == 1 else 'entries hide'} "
            f"{FIELD_WORDS.get(name, name)} ({why}){ids}."
        )
    if lines or report.hidden.get("role"):
        lines.append(
            "A hidden field's value can't be read or confirmed here, but each entry's hash covers it through "
            "the digest the export gives, so a change to it would still show. Every entry hides the actor's "
            "account role, which no export shows."
        )
    return lines


# What a file that isn't an export can raise while it is read or checked, besides ExportError.
_UNREADABLE = (
    ValueError,
    TypeError,
    KeyError,
    AttributeError,
    IndexError,
    RecursionError,
    OverflowError,
    csv.Error,
)


def main(argv: Sequence[str] | None = None) -> int:
    parser = argparse.ArgumentParser(
        prog="verify-audit-export.py",
        description="Check an Everdeck audit log export (CSV or JSON Lines) against its hash chain.",
    )
    parser.add_argument("export", help="the export to check")
    parser.add_argument("--previous", help="an older export of the same log that you kept, to compare with")
    parser.add_argument(
        "--as-of",
        help="count entries' ages to this time (ISO 8601 with an offset) instead of when the newer file was made; "
        "never later than that",
    )
    parser.add_argument("--list", action="store_true", help="list the ids of every entry that hides a field")
    args = parser.parse_args(argv)
    out = sys.stdout
    now = datetime.now(_UTC)
    try:
        export = read_export(args.export)
        print(_describe(export), file=out)
        report = check(export, now=now)
        if args.previous:
            older = read_export(args.previous)
            print(_describe(older), file=out)
            for line in check(older, now=now).problems:
                report.problems.append(f"In the older file: {line}")
            as_of = export.made(now)
            if args.as_of:
                as_of = min(as_of, _when(args.as_of, "--as-of"))
            compared = compare(older, export, as_of=as_of)
            report.problems += compared.problems
            report.notes += compared.notes
    except ExportError as err:
        print(f"Couldn't check: {safe(err)}", file=sys.stderr)
        return 2
    except _UNREADABLE as err:
        print(
            f"Couldn't check: the file isn't an export this script can read ({type(err).__name__}: {safe(err)[:200]})",
            file=sys.stderr,
        )
        return 2
    print(
        f"Checked {report.checked:,} {'hash' if report.checked == 1 else 'hashes'} and {report.linked:,} "
        f"{'link' if report.linked == 1 else 'links'} between entries.",
        file=out,
    )
    for line in report.unchecked + _hidden_lines(report, listing=args.list) + report.notes:
        print(f"- {line}", file=out)
    for line in report.problems:
        print(f"PROBLEM: {line}", file=out)
    if report.problems:
        print(
            f"{len(report.problems):,} {'problem' if len(report.problems) == 1 else 'problems'} found.",
            file=out,
        )
        return 1
    print("No problems found.", file=out)
    return 0


if __name__ == "__main__":
    sys.exit(main())
