"""Contract lock file generation.

Produces a deterministic contracts.lock.json listing each schema file
with its SHA-256 digest.  The output is byte-stable: regenerating the
lock from unchanged schemas always produces identical bytes.
"""

from __future__ import annotations

import hashlib
import json
from typing import Any

from abi_control_core.contracts import CONTRACTS_DIR


def generate_lock() -> dict[str, Any]:
    """Generate lock data for all contract schema files.

    Returns:
        Dict with 'contracts' (sorted list of {name, sha256}).
        No timestamps — output is deterministic and byte-stable.
    """
    contracts: list[dict[str, str]] = []

    for schema_file in sorted(CONTRACTS_DIR.glob("*.schema.json")):
        raw = schema_file.read_bytes().replace(b"\r\n", b"\n")
        digest = hashlib.sha256(raw).hexdigest()
        contracts.append({
            "name": schema_file.name,
            "sha256": digest,
        })

    return {
        "contracts": contracts,
    }


def serialize_lock(lock_data: dict[str, Any]) -> str:
    """Serialize lock data to deterministic JSON text (with trailing newline)."""
    return json.dumps(lock_data, indent=2) + "\n"
