"""
LÁR COMPLIANCE PATTERN: Audit Log Verifier

USAGE:
This is a standalone verification script used by Compliance Officers or Auditors
to cryptographically prove that an execution log has not been tampered with.

Run this script from the terminal, passing the path to the log and the secret key:
    python 11_verify_audit_log.py path/to/run_xyz.json super_secret_enterprise_key_123
"""

import sys
import json
import hmac
import hashlib
import os

def verify_log(log_path: str, secret_key: str):
    """
    Verifies the HMAC-SHA256 signature of a Lár JSON audit log.
    """
    if not os.path.exists(log_path):
        print(f"[!] Error: File not found at {log_path}")
        sys.exit(1)

    with open(log_path, "r") as f:
        try:
            log_data = json.load(f)
        except json.JSONDecodeError:
            print("[!] Error: Invalid JSON file.")
            sys.exit(1)

    print("\n" + "="*50)
    print("LAR AUDIT LOG INTEGRITY VERIFIER")
    print("="*50)
    print(f"[i] Checking file: {log_path}\n")

    # 1. Extract the signature generated by Lár
    saved_signature = log_data.get("signature")
    if not saved_signature:
        print("[VERIFICATION FAILED]: No cryptographic signature found in this log.")
        sys.exit(1)
        
    print(f"1. Signature found in log: {saved_signature}")

    # 2. Canonicalize the payload (perfectly reproduce the state of the JSON when it was signed)
    clean_payload = {k: v for k, v in log_data.items() if k != "signature"}
    payload_str = json.dumps(clean_payload, sort_keys=True, separators=(',', ':'))

    # 3. Compute the HMAC-SHA256 Hash
    mac = hmac.new(
        key=secret_key.encode('utf-8'),
        msg=payload_str.encode('utf-8'),
        digestmod=hashlib.sha256,
    )
    computed_signature = mac.hexdigest()

    print(f"2. Re-computed signature:  {computed_signature}\n")

    # 4. Compare
    if saved_signature == computed_signature:
        print("[+] VERIFICATION SUCCESSFUL")
        print("    The audit log is fully authentic and has not been tampered with.")
        sys.exit(0)
    else:
        print("[-] VERIFICATION FAILED")
        print("    The audit log is corrupt or was maliciously tampered with.")
        sys.exit(1)

if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("Usage: python verify_audit_log.py <path_to_json> <hmac_secret>")
        sys.exit(1)
        
    log_file = sys.argv[1]
    hmac_key = sys.argv[2]
    
    verify_log(log_file, hmac_key)
