"""Read local C2PA data without transforming the input or deciding authorship.

Requires c2pa-python==0.38.0. Exit 0 means a report was read, not that
the signer is trusted or the asset is human-created. Exit 2 is inconclusive.
"""

import argparse
import hashlib
import json
from pathlib import Path
import sys

from c2pa import Context, Reader


def sha256_file(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as source:
        for chunk in iter(lambda: source.read(65536), b""):
            digest.update(chunk)
    return digest.hexdigest()


def inspect_file(path: Path) -> dict:
    before = sha256_file(path)
    try:
        with Context.from_dict({
            "verify": {
                "remote_manifest_fetch": False,
                "ocsp_fetch": False,
                "verify_trust": False,
                "verify_timestamp_trust": False,
            }
        }) as context:
            with Reader(str(path), context=context) as reader:
                manifest_store = json.loads(reader.json())
        result = {
            "status": "manifest_report_read",
            "manifest_store": manifest_store,
        }
    except Exception as error:
        result = {
            "status": "inconclusive",
            "error_type": type(error).__name__,
            "error": str(error),
        }

    after = sha256_file(path)
    if before != after:
        raise RuntimeError("Input bytes changed during inspection")
    return {
        "file": path.name,
        "sha256": before,
        "input_unchanged": True,
        "scope": "Local manifest inspection; signer trust is not established; no authorship verdict",
        **result,
    }


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("asset", type=Path)
    args = parser.parse_args()
    try:
        result = inspect_file(args.asset)
    except (OSError, RuntimeError) as error:
        result = {
            "status": "inconclusive",
            "error_type": type(error).__name__,
            "error": str(error),
        }
    print(json.dumps(result, ensure_ascii=False, indent=2))
    return 0 if result["status"] == "manifest_report_read" else 2


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