"""Worked example: an agent prepares a VAT return, a person approves it, and the tax authority (a counterparty with no login to anything of ours) checks it offline.

Three roles, three steps:
  1. The agent prepares the return (a plain JSON payload).
  2. The company's own system records the person's approval and issues a credential. Here the company signs with its OWN key, not FLOCORE's: the format is open.
     (This step uses FLOCORE's issuing code from apps/api; any implementation that emits the same credential works.)
  3. The counterparty receives the return and the credential and verifies them with packages/humanseal-verify/humanseal_verify.py alone: one file, the
     company's published public key, no call to anyone.

Run from the repository root:   cd apps/api && python ../../examples/invoice-vat-approval/example.py
"""
import base64
import importlib.util
import os
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.abspath(os.path.join(HERE, "..", ".."))


def _load_verifier():
    spec = importlib.util.spec_from_file_location("humanseal_verify", os.path.join(ROOT, "packages", "humanseal-verify", "humanseal_verify.py"))
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)
    return mod


COMPANY_DID = "did:web:books.example-company.test"
VAT_RETURN = {"type": "vat_return", "period": "2026-09", "currency": "ZAR", "output_vat": 184250.00, "input_vat": 121900.50, "payable": 62349.50,
              "prepared_by": "agent:books-assistant"}


def run(*, tamper: bool = False) -> dict:
    sys.path.insert(0, os.path.join(ROOT, "apps", "api"))
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
    from cryptography.hazmat.primitives.serialization import Encoding, NoEncryption, PrivateFormat
    from app.services import human_seal as hs
    from app.services import vc_receipts as vc
    from app.services.receipt_signing import ReceiptSigner

    # The company's own signing key. Its public half is what it publishes (here as a JWKS the counterparty already holds).
    raw = Ed25519PrivateKey.generate().private_bytes(Encoding.Raw, PrivateFormat.Raw, NoEncryption())
    signer = ReceiptSigner(base64.urlsafe_b64encode(raw).decode().rstrip("="))
    kid = COMPANY_DID + "#key-1"
    published_jwks = {"keys": [{"kty": "OKP", "crv": "Ed25519", "x": signer.public_key_b64(), "use": "sig", "alg": "EdDSA", "kid": kid}]}

    # Step 2: a person approved this exact return, so the credential is bound to its content hash.
    receipt = hs.issue(signer, action_id="vat-2026-09", action_type="vat_return", action_payload=VAT_RETURN, tenant="example-company",
                       approver_ref=hs.approver_ref_for("finance-manager-1"), approver_type="human_session",
                       oversight={"risk_tier": "high", "decision_latency_ms": 41000, "rationale": "checked totals against the ledger"})
    token = vc.issue_sd_jwt_vc(signer, receipt, issuer=COMPANY_DID, kid=kid, vct="https://example-company.test/vct/approval/v1").issuance

    # Step 3: the counterparty gets the return (possibly altered on the way) and the credential.
    received = dict(VAT_RETURN, payable=1.00) if tamper else VAT_RETURN
    verifier = _load_verifier()
    verdict = verifier.verify(token, published_jwks, action=received, issuer=COMPANY_DID, vct="https://example-company.test/vct/approval/v1")
    return {"token": token, "verdict": verdict}


if __name__ == "__main__":
    for label, tamper in (("as sent", False), ("payable changed after approval", True)):
        v = run(tamper=tamper)["verdict"]
        print(f"{label}: valid={v['valid']}  {v['reason']}")
