"""Hashline utilities for file editing with optimistic locking.

Hashline format: {line_num}:{hash}|{content}
Example:
    1:a3f|function hello() {
    2:f1b|  return "world";
    3:0e2|}

The hash is a 3-char hex derived from line content, enabling
optimistic locking for edits.
"""

from __future__ import annotations

import zlib


def hash_line(line: str) -> str:
    """Generate 3-char hex hash from line content.

    Uses CRC32 truncated to 12 bits (4096 possible values).
    Collision rate is acceptable for single-file editing context.
    """
    return format(zlib.crc32(line.encode()) & 0xFFF, '03x')


def format_hashline(line_num: int, content: str) -> str:
    """Format a line as hashline: {line_num}:{hash}|{content}"""
    h = hash_line(content)
    return f"{line_num}:{h}|{content}"


def format_hashlines(lines: list[str], start_num: int = 1) -> str:
    """Format multiple lines as hashlines."""
    result = []
    for i, line in enumerate(lines, start=start_num):
        result.append(format_hashline(i, line))
    return "\n".join(result)
