"""Simple JSON file storage utilities with basic locking."""

import json
import os
import threading
from typing import Any, Dict, List, Optional

_locks: Dict[str, threading.Lock] = {}


def _get_lock(path: str) -> threading.Lock:
    if path not in _locks:
        _locks[path] = threading.Lock()
    return _locks[path]


def ensure_dir(path: str) -> None:
    directory = os.path.dirname(path)
    if directory and not os.path.exists(directory):
        os.makedirs(directory, exist_ok=True)


def read_json(path: str, default: Any) -> Any:
    lock = _get_lock(path)
    with lock:
        if not os.path.exists(path):
            return default
        with open(path, "r", encoding="utf-8") as f:
            try:
                return json.load(f)
            except json.JSONDecodeError:
                return default


def write_json(path: str, data: Any) -> None:
    ensure_dir(path)
    lock = _get_lock(path)
    with lock:
        with open(path, "w", encoding="utf-8") as f:
            json.dump(data, f, indent=2)


