#!/usr/bin/env python3
"""93 evidence: send evidence to 93 Compliance from the job that produces it (open source, Python 3, no packages).

  export NINETYTHREE_EVIDENCE_KEY=93ek_...        # from your administrator (one evidence item per key)
  python3 93-evidence.py submit report.pdf                      # the file is stored by 93; fingerprinted here first
  python3 93-evidence.py submit --hash-only backup.log          # only the SHA-256 leaves your network
  python3 93-evidence.py submit --failed --note "backup failed"   # the job ran and failed: say so
  python3 93-evidence.py submit report.pdf --receipt-out receipt.json

Every submission gets a 93 Notary receipt (signed, in a log timestamped by outside authorities). Check it at
https://93problems.com/notary/verify or offline with notary_verify.py. Exit code 0 = accepted.
"""
import argparse
import hashlib
import json
import mimetypes
import os
import platform
import sys
import urllib.error
import urllib.request
import uuid

API = os.environ.get("NINETYTHREE_API", "https://93problems.com/api")
VERSION = "1.0"


def sha256_of(path):
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()


def multipart(fields, file=None):
    b = uuid.uuid4().hex
    out = []
    for k, v in fields.items():
        if v is None:
            continue
        out += [f"--{b}".encode(), f'Content-Disposition: form-data; name="{k}"'.encode(), b"", str(v).encode()]
    if file:
        name = os.path.basename(file)
        ctype = mimetypes.guess_type(name)[0] or "application/octet-stream"
        with open(file, "rb") as f:
            data = f.read()
        out += [f"--{b}".encode(), f'Content-Disposition: form-data; name="file"; filename="{name}"'.encode(),
                f"Content-Type: {ctype}".encode(), b"", data]
    out += [f"--{b}--".encode(), b""]
    return b"\r\n".join(out), f"multipart/form-data; boundary={b}"


def submit(a):
    key = os.environ.get("NINETYTHREE_EVIDENCE_KEY", "")
    if not key.startswith("93ek_"):
        sys.exit("Set NINETYTHREE_EVIDENCE_KEY to your evidence key (93ek_...).")
    if not a.file and not a.failed:
        sys.exit("Give a file, or --failed with a --note.")
    if a.file and not os.path.isfile(a.file):
        sys.exit(f"No such file: {a.file}")
    if a.file:
        digest = sha256_of(a.file)
    else:   # a failure with no file: fingerprint the note
        digest = hashlib.sha256((a.note or "failed").encode()).hexdigest()
    if a.file and not a.hash_only and os.path.getsize(a.file) > 25 * 1024 * 1024:
        sys.exit("The file is larger than 25 MB: send it with --hash-only.")
    fields = {"sha256": digest, "status": "failed" if a.failed else "ok", "note": a.note,
              "name": os.path.basename(a.file) if a.file else None,
              "source": a.source or f"93-evidence/{VERSION} ({platform.node()})"}
    body, ctype = multipart(fields, None if (a.hash_only or not a.file) else a.file)
    req = urllib.request.Request(f"{API}/evidence/submit", data=body, method="POST",
                                 headers={"Authorization": f"Bearer {key}", "Content-Type": ctype,
                                          "User-Agent": f"93-evidence/{VERSION}"})
    try:
        with urllib.request.urlopen(req, timeout=120) as r:
            out = json.load(r)
    except urllib.error.HTTPError as e:
        try:
            detail = json.load(e).get("detail")
        except Exception:
            detail = e.reason
        sys.exit(f"Refused ({e.code}): {detail}")
    except urllib.error.URLError as e:
        sys.exit(f"Couldn't reach {API}: {e.reason}")
    rc = out.get("receipt") or {}
    print(f"accepted: {out['status']}{' (hash only)' if out.get('hash_only') else ''}  sha256 {out['sha256']}")
    if rc:
        print(f"receipt: {rc.get('leaf_hash')}  (check at https://93problems.com/notary/verify)")
    if a.receipt_out:
        with open(a.receipt_out, "w") as f:
            json.dump(rc or out, f, indent=1)


def main():
    ap = argparse.ArgumentParser(prog="93-evidence", description="Send evidence to 93 Compliance.")
    sub = ap.add_subparsers(dest="cmd", required=True)
    s = sub.add_parser("submit", help="send one piece of evidence")
    s.add_argument("file", nargs="?")
    s.add_argument("--expectation", help="the evidence item id (for your records; the key decides where it goes)")
    s.add_argument("--hash-only", action="store_true", help="send only the SHA-256; the file stays with you")
    s.add_argument("--failed", action="store_true", help="the job ran and failed")
    s.add_argument("--note", help="a short note (no personal or patient data)")
    s.add_argument("--source", help="where it came from (default: this tool and host name)")
    s.add_argument("--receipt-out", help="save the 93 Notary receipt to this file")
    a = ap.parse_args()
    if a.cmd == "submit":
        submit(a)


if __name__ == "__main__":
    main()
