#!/usr/bin/env python3
"""Compare one file's SHA-256 digest with an expected hexadecimal value."""

from __future__ import annotations

from hashlib import sha256
from hmac import compare_digest
from pathlib import Path
import re
import sys


def main() -> int:
    if len(sys.argv) != 3:
        print("usage: python check_sha256.py EXPECTED_SHA256 FILE", file=sys.stderr)
        return 2

    expected = sys.argv[1].lower()
    path = Path(sys.argv[2])
    if re.fullmatch(r"[0-9a-f]{64}", expected) is None:
        print("error: EXPECTED_SHA256 must be exactly 64 hexadecimal characters", file=sys.stderr)
        return 2
    if not path.is_file():
        print(f"error: file not found: {path}", file=sys.stderr)
        return 2

    actual = sha256(path.read_bytes()).hexdigest()
    matches = compare_digest(actual, expected)
    print(f"file: {path}")
    print(f"expected: {expected}")
    print(f"actual:   {actual}")
    print(f"result:   {'MATCH' if matches else 'MISMATCH'}")
    return 0 if matches else 1


if __name__ == "__main__":
    raise SystemExit(main())
