from __future__ import annotations

"""Author: Vasiliy Zdanovskiy
email: vasilyvz@gmail.com

SHA-256 checksum helpers for transfer integrity (canonical uncompressed bytes).
"""

from hashlib import sha256

from mcp_proxy_adapter.transfer.errors import TransferChecksumMismatchError
from mcp_proxy_adapter.transfer.errors import TransferError

DEFAULT_CHUNK_SIZE: int = 1048576


def compute_file_checksum(
    path: str, algorithm: str = "sha256", chunk_size: int = DEFAULT_CHUNK_SIZE
) -> str:
    if algorithm != "sha256":
        raise TransferError(
            f'Unsupported checksum algorithm: {algorithm!r} (only "sha256" is supported)',
            phase="checksum",
        )
    if chunk_size <= 0:
        raise TransferError("chunk_size must be > 0", phase="checksum")
    h = sha256()
    with open(path, "rb") as f:
        while True:
            chunk = f.read(chunk_size)
            if not chunk:
                break
            h.update(chunk)
    return h.hexdigest()


def verify_file_checksum(
    path: str,
    expected_checksum: str,
    algorithm: str = "sha256",
    chunk_size: int = DEFAULT_CHUNK_SIZE,
    transfer_id: str | None = None,
    phase: str = "verify",
) -> None:
    actual = compute_file_checksum(path, algorithm=algorithm, chunk_size=chunk_size)
    if actual != expected_checksum:
        raise TransferChecksumMismatchError(
            "Checksum mismatch",
            transfer_id=transfer_id,
            checksum_expected=expected_checksum,
            checksum_actual=actual,
            phase=phase,
        )
