# MIT License
#
# Copyright (c) 2026 Oneiros Vision Research S.R.L.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""Checks an Oneiros Vision mandate record export offline, with nothing but Python.

Recomputes every entry's SHA-256 digest from the entry before it and the
fields its type is hashed over, checks every link of every book's chain, and
checks each chain's last digest against the export's manifest. Given the
manifest of an EARLIER export (--previous-heads), it also checks that each
chain still holds the entries that export held, unchanged: a chain cut short
at the end, or rewritten since, verifies on its own as a clean shorter chain,
and only a copy kept outside the record shows that.

It is an independent implementation of the rule the record states, written
for this purpose: standard library only, Python 3.9 or later, no network. It
reads the record; it changes nothing.

Usage:
    python ov_verify_record.py <export.zip or its unpacked folder>
    python ov_verify_record.py <export.zip> --previous-heads <earlier export.zip or its manifest.json>

Exit codes:
    0   every digest recomputed and every check passed
    1   a check failed; the first failure of each book is printed
    2   the export could not be read
"""

from __future__ import annotations

import argparse
import hashlib
import json
import sys
import zipfile
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple

#: The digest a book's first entry is chained onto.
GENESIS = "0" * 64

#: The formats this verifier reads.
FORMATS = ("oneiros-vision-firm-record/1",)

_MEASUREMENT_V1 = (
    "entry_type", "entry_date", "portfolio_id", "regime", "mdi", "var_95_pct", "drawdown_bound_95_pct",
    "sleeve_mix", "mandate_configured", "mandate_results", "mandate_breaches", "depreciation_state",
    "depreciation_change_pct", "depreciation_estimated", "alerts_sent",
)
_MEASUREMENT_V2 = _MEASUREMENT_V1 + ("record_version", "coverage")
_MEASUREMENT_V3 = _MEASUREMENT_V2 + (
    "book_version_id", "holdings_saved_at", "holdings_as_of", "currency", "drawdown_method", "method_version",
    "stated_tolerance_pct",
)
_MEASUREMENT_V4 = _MEASUREMENT_V3 + ("rules_due",)
_MEASUREMENT_V5 = _MEASUREMENT_V4 + ("forward_liability_counts",)
_MEASUREMENT_V6 = _MEASUREMENT_V5 + ("session_source", "recorded_late", "recorded_at", "carried")
_MEASUREMENT_V7 = _MEASUREMENT_V6 + ("depreciation_value_basis", "depreciation_on_bases")
_ACKNOWLEDGEMENT = ("entry_type", "entry_date", "portfolio_id", "actor", "note", "acknowledged_at")
_GOVERNANCE = (
    "entry_type", "entry_date", "portfolio_id", "record_version", "actor", "actor_role", "field", "before", "after",
    "note", "changed_at",
)
_ATTESTATION = (
    "entry_type", "entry_date", "portfolio_id", "record_version", "attestation_id", "period_start", "period_end",
    "sessions_covered", "open_breaches_noted", "actor", "actor_role", "note", "attested_at", "step_up",
)
_ATTESTATION_V2 = _ATTESTATION + ("document_sha256", "document_label")
_CLIENT_NOTICE = (
    "entry_type", "entry_date", "portfolio_id", "record_version", "actor", "actor_role", "sent_on", "channel",
    "threshold_reference", "note", "recorded_at",
)
_DRILL = (
    "entry_type", "entry_date", "portfolio_id", "record_version", "actor", "actor_role", "window_name",
    "window_first", "window_last", "rules_entry_digest", "fired", "max_open_windows", "not_replayed", "note",
    "recorded_at",
)

#: The newest record version of each versioned type this copy of the checker reads. An entry written with
#: a later one is newer than this checker, not a fault: the export it came in carries the checker that reads it.
_NEWEST_VERSION = {"measurement": 7, "attestation": 2}


def expected_columns(entry_type: str, payload: Dict[str, Any]) -> Optional[Tuple[str, ...]]:
    """The fields an entry is hashed over, by its type and its payload's version; None for an unknown type.

    A measurement with record_version 7 over the version-7 set, 6 over the version-6 set, 5 over the
    version-5 set, 4 over the version-4 set, 3 over the version-3 set, 2 over
    the version-2 set, any other over the first; an
    acknowledgement carrying rule_id over the set with the role and the rule,
    one carrying actor_role over the set with the role; an attestation with
    record_version 2 over the version-2 set, any other over the first; the
    other types over their own.
    """
    if entry_type == "measurement":
        version = payload.get("record_version")
        if version == 7 and not isinstance(version, bool):
            return _MEASUREMENT_V7
        if version == 6 and not isinstance(version, bool):
            return _MEASUREMENT_V6
        if version == 5 and not isinstance(version, bool):
            return _MEASUREMENT_V5
        if version == 4 and not isinstance(version, bool):
            return _MEASUREMENT_V4
        if version == 3 and not isinstance(version, bool):
            return _MEASUREMENT_V3
        if version == 2 and not isinstance(version, bool):
            return _MEASUREMENT_V2
        return _MEASUREMENT_V1
    if entry_type == "acknowledgement":
        if "rule_id" in payload:
            return _ACKNOWLEDGEMENT + ("actor_role", "rule_id")
        return _ACKNOWLEDGEMENT + ("actor_role",) if "actor_role" in payload else _ACKNOWLEDGEMENT
    if entry_type == "attestation":
        version = payload.get("record_version")
        if version == 2 and not isinstance(version, bool):
            return _ATTESTATION_V2
        return _ATTESTATION
    return {
        "governance": _GOVERNANCE,
        "client_notice": _CLIENT_NOTICE,
        "drill": _DRILL,
    }.get(entry_type)


def newer_than_checker(entry_type: str, payload: Dict[str, Any]) -> Optional[str]:
    """Why this copy of the checker cannot read an entry, or None where it can.

    An entry type this checker does not know, or a record version after the
    ones it reads, means the entry was written after this checker was: the
    export the entry came in ships the checker that reads it.
    """
    version = payload.get("record_version")
    newest = _NEWEST_VERSION.get(entry_type)
    if newest is not None and isinstance(version, int) and not isinstance(version, bool) and version > newest:
        return f"was written with record version {version}, newer than this checker"
    if expected_columns(entry_type, payload) is None:
        return f"was written with an entry type {entry_type!r} newer than this checker"
    return None


def render(value: Any) -> str:
    """One field as it enters the digest.

    None as the empty string; true and false as True and False; a float to 12
    significant digits; an object or list as JSON with sorted keys, ',' and
    ':' as the only separators and every character beyond ASCII escaped;
    anything else as its text.
    """
    if value is None:
        return ""
    if isinstance(value, bool):
        return "True" if value else "False"
    if isinstance(value, float):
        return format(value, ".12g")
    if isinstance(value, (dict, list)):
        return json.dumps(value, sort_keys=True, separators=(",", ":"))
    return str(value)


def digest_of(prev_digest: str, payload: Dict[str, Any], columns: Sequence[str]) -> str:
    """SHA-256 over the previous digest and the entry's fields, joined by '|'."""
    text = prev_digest + "|" + "|".join(render(payload.get(column)) for column in columns)
    return hashlib.sha256(text.encode("utf-8")).hexdigest()


class Unreadable(Exception):
    """The export cannot be read as one."""


def _read_member(source: Path, name: str) -> str:
    if source.is_dir():
        path = source / name
        if not path.is_file():
            raise Unreadable(f"{name} is not in {source}")
        return path.read_text(encoding="utf-8")
    try:
        with zipfile.ZipFile(source) as archive:
            return archive.read(name).decode("utf-8")
    except KeyError:
        raise Unreadable(f"{name} is not in {source}") from None
    except (zipfile.BadZipFile, OSError) as error:
        raise Unreadable(f"{source} is not an export: {error}") from None


def read_manifest(source: Path) -> Dict[str, Any]:
    """An export's manifest, from the export itself or from a manifest.json kept on its own."""
    if source.is_file() and source.suffix.lower() == ".json":
        text = source.read_text(encoding="utf-8")
    else:
        text = _read_member(source, "manifest.json")
    try:
        manifest = json.loads(text)
    except ValueError as error:
        raise Unreadable(f"the manifest is not JSON: {error}") from None
    if manifest.get("format") not in FORMATS:
        raise Unreadable(f"the manifest's format {manifest.get('format')!r} is not one this verifier reads")
    return manifest


def read_entries(source: Path) -> List[Dict[str, Any]]:
    """Every entry line of an export, in the order written."""
    entries = []
    for number, line in enumerate(_read_member(source, "entries.jsonl").splitlines(), start=1):
        if not line.strip():
            continue
        try:
            entry = json.loads(line)
        except ValueError:
            raise Unreadable(f"entries.jsonl line {number} is not JSON") from None
        if not isinstance(entry, dict):
            raise Unreadable(f"entries.jsonl line {number} is not an entry")
        entries.append(entry)
    return entries


def check_chain(book_id: str, entries: Sequence[Dict[str, Any]]) -> Optional[str]:
    """The first fault in one book's chain, or None where every digest recomputes and every link holds."""
    prev = GENESIS
    for position, entry in enumerate(entries, start=1):
        label = f"entry {position} (id {entry.get('id')}, {entry.get('entry_date')})"
        payload = entry.get("payload")
        if not isinstance(payload, dict):
            return f"{label} carries no payload"
        listed = tuple(entry.get("columns") or ())
        newer = newer_than_checker(str(entry.get("entry_type")), payload)
        if newer is not None:
            return f"{label} {newer}; use the ov_verify_record.py inside the export"
        known = expected_columns(str(entry.get("entry_type")), payload)
        if known is None:
            return f"{label} was written with an entry type newer than this checker; use the ov_verify_record.py inside the export"
        if listed != known:
            return f"{label} lists other fields than its type and version are hashed over"
        if entry.get("prev_digest") != prev:
            return f"{label} was chained onto another entry than the one before it: an entry is missing or moved"
        recomputed = digest_of(prev, payload, known)
        if recomputed != entry.get("digest"):
            return f"{label} does not recompute to its digest: it was altered after it was written"
        prev = recomputed
    return None


def group(entries: Iterable[Dict[str, Any]]) -> Dict[str, List[Dict[str, Any]]]:
    books: Dict[str, List[Dict[str, Any]]] = {}
    for entry in entries:
        books.setdefault(str(entry.get("book_id")), []).append(entry)
    return books


def verify(source: Path, previous: Optional[Path] = None, out=sys.stdout) -> int:
    """Checks one export; returns the exit code."""
    try:
        manifest = read_manifest(source)
        books = group(read_entries(source))
        earlier = read_manifest(previous) if previous else None
    except Unreadable as error:
        print(f"UNREADABLE: {error}", file=out)
        return 2

    listed = {str(b.get("book_id")): b for b in manifest.get("books") or []}
    faults = 0
    total = 0
    for book_id in sorted(set(listed) | set(books)):
        chain = books.get(book_id, [])
        total += len(chain)
        fault = check_chain(book_id, chain)
        stated = listed.get(book_id)
        if fault is None and stated is None:
            fault = "the manifest does not list this book"
        if fault is None:
            head = chain[-1]["digest"] if chain else None
            if stated.get("head_digest") != head or int(stated.get("entries", -1)) != len(chain):
                fault = "its last digest or its entry count is not the one the manifest states"
        if fault is None and earlier is not None:
            fault = _against_earlier(book_id, chain, earlier)
        if fault:
            faults += 1
            print(f"FAIL  {book_id}: {fault}", file=out)
        else:
            print(f"OK    {book_id}: {len(chain)} entries", file=out)

    if earlier is not None:
        now = set(books)
        for gone in sorted(str(b.get("book_id")) for b in earlier.get("books") or [] if str(b.get("book_id")) not in now):
            faults += 1
            print(f"FAIL  {gone}: in the earlier export, not in this one", file=out)

    if faults:
        print(f"{faults} book(s) failed; {total} entries read.", file=out)
        return 1
    witness = " and every chain still holds the earlier export's entries" if earlier is not None else ""
    print(f"Every digest recomputed: {len(books)} book(s), {total} entries{witness}.", file=out)
    return 0


def _against_earlier(book_id: str, chain: Sequence[Dict[str, Any]], earlier: Dict[str, Any]) -> Optional[str]:
    """Whether the chain still holds, unchanged, the entries an earlier export's manifest states for the book."""
    before = next((b for b in earlier.get("books") or [] if str(b.get("book_id")) == book_id), None)
    if before is None:
        return None
    count = int(before.get("entries", 0))
    if count == 0:
        return None
    if len(chain) < count:
        return f"it holds {len(chain)} entries; the earlier export held {count}: the chain was cut short"
    if chain[count - 1].get("digest") != before.get("head_digest"):
        return "its entry where the earlier export ended is not the one that export held: the chain was rewritten"
    return None


def main(argv: Optional[Sequence[str]] = None) -> int:
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("export", type=Path, help="the export (.zip) or the folder it was unpacked to")
    parser.add_argument(
        "--previous-heads", type=Path, default=None,
        help="an earlier export, or its manifest.json, to check this one still holds its entries",
    )
    args = parser.parse_args(argv)
    return verify(args.export, args.previous_heads)


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