"""Actual local encrypted evidence lifecycle; no model or external account required."""
from __future__ import annotations
import json
import os
from pathlib import Path
import sys
import tempfile
import time
from soterias import Citation, FactReference, SourceStore, SourceStoreError


def main() -> None:
    started = time.perf_counter_ns()
    root = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(tempfile.mkdtemp(prefix="soterias-evidence-"))
    root.mkdir(parents=True, exist_ok=True)
    original = root / "invoice.txt"
    text = "Invoice INV-42: café 😀; amount 120.00 EUR.\n"
    original.write_bytes(text.encode("utf-8"))
    # Disposable local example secret, deliberately not a production credential.
    unlock = b"disposable-local-evidence-example"
    store = SourceStore.create(root / "store", passphrase=unlock, tenant_id="demo", store_id="audit")
    now = time.time_ns() // 1_000_000
    source = store.ingest_file(original, media="utf8_text", permitted_uses=["transaction-testing"], captured_at_ms=now)
    # Production hosts protect the checkpoint independently from the store itself.
    checkpoint_path = root / "checkpoint.json"
    checkpoint_path.write_bytes(store.checkpoint())
    evidence = store.evidence(principal="auditor", purpose="transaction-testing")
    evidence.register_source(source, identity="invoice-42", revision="v1", readers=["auditor"],
                             stale_after_ms=now + 60_000, retain_until_ms=now + 120_000)
    checkpoint_path.write_bytes(store.checkpoint())
    quoted = "120.00 EUR"
    start = text.index(quoted)  # Python Unicode scalar indices, not UTF-8 bytes.
    citation = Citation(source, start=start, end=start + len(quoted), quote=quoted)
    assert evidence.verify(citation)["status"] == "verified"
    proof = store.verify_quote(source, purpose="transaction-testing", start=start,
                               end=start + len(quoted), quote=quoted, current_file=original)
    literal = evidence.extract_quote(citation)
    (root / "fact-id.txt").write_text(literal.digest, encoding="ascii")
    checkpoint_path.write_bytes(store.checkpoint())
    checked = evidence.check_fact(literal)
    assert checked["report"]["quotation_truth"] == "true"
    assert checked["report"]["semantic_truth"] == "not_established"
    interpretation = evidence.extract_interpretation("The transaction is valid", citations=[citation])
    checkpoint_path.write_bytes(store.checkpoint())
    assert evidence.check_fact(interpretation)["report"]["quotation_truth"] == "unknown"
    assert evidence.check_fact(FactReference("0" * 64))["truth"] == "unknown"
    try:
        store.evidence(principal="other-agent", purpose="transaction-testing").verify(citation)
    except SourceStoreError as error:
        assert error.code == "evidence_use_denied"
    else:
        raise AssertionError("reader permission was not enforced")
    original.write_bytes((text + "changed outside quote\n").encode("utf-8"))
    try:
        store.verify_quote(source, purpose="transaction-testing", start=start,
                           end=start + len(quoted), quote=quoted, current_file=original)
    except SourceStoreError as error:
        assert error.code == "evidence_original_changed"
    else:
        raise AssertionError("whole-current-source mutation was not refused")
    # Historical provenance remains explicit and does not assert a current original.
    assert evidence.verify(citation)["status"] == "verified"
    store.close()
    with SourceStore.open(root / "store", passphrase=unlock, checkpoint=checkpoint_path.read_bytes()) as reopened:
        evidence = reopened.evidence(principal="auditor", purpose="transaction-testing")
        assert evidence.check_fact(literal)["report"]["quotation_truth"] == "true"
        evidence.revoke_source(source)
        checkpoint_path.write_bytes(reopened.checkpoint())
        try:
            evidence.check_fact(literal)
        except SourceStoreError as error:
            assert error.code == "evidence_source_revoked"
        else:
            raise AssertionError("revocation did not invalidate dependent fact")
    pure = SourceStore.check_quote(text.encode("utf-8"), start=start, end=start + len(quoted), quote=quoted)
    print(json.dumps({"status": "PASS", "runtime": "python", "mode": "cooperative_host_integrity",
                      "quotation_proof": proof["digest"], "pure_check": pure,
                      "elapsed_ms": (time.perf_counter_ns() - started) / 1_000_000,
                      "model_calls": 0, "provider_tokens": None,
                      "semantic_truth": "not_established", "root": os.fspath(root)}))


if __name__ == "__main__":
    main()
