from __future__ import annotations

import json
from pathlib import Path
from typing import Any, Callable


LineHandler = Callable[[Path, str, dict[str, Any] | None], None]


def consume_event_file(path: Path, *, offset: int, on_line: LineHandler) -> int:
    with path.open("r", encoding="utf-8", errors="replace") as f:
        f.seek(offset)
        for line in f:
            text = line.rstrip("\n")
            if not text:
                continue
            payload: dict[str, Any] | None
            try:
                raw = json.loads(text)
            except json.JSONDecodeError:
                payload = None
            else:
                payload = raw if isinstance(raw, dict) else None
            on_line(path, text, payload)
        return f.tell()


def ensure_offset(path: Path, *, offsets: dict[Path, int], history: bool) -> int:
    if path not in offsets:
        offsets[path] = 0 if history else path.stat().st_size
    return offsets[path]
