"""
JSON handler: read/write resource dicts as JSON files under a directory.
"""

import json
import os
from pathlib import Path


def read_resources(
    resource_dir: str | Path,
    *,
    name_key: str = "name",
    file_extension: str = ".json",
) -> list[dict]:
    """
    Read all JSON files from a resource directory and return a list of dicts.
    Each file is expected to contain a single JSON object (e.g. one resource).
    Filenames are ignored for ordering; use name_key inside each object for identity.
    """
    path = Path(resource_dir).resolve()
    if not path.is_dir():
        return []
    items = []
    for f in sorted(path.glob(f"*{file_extension}")):
        try:
            with open(f) as fp:
                data = json.load(fp)
            if isinstance(data, dict):
                items.append(data)
        except (OSError, json.JSONDecodeError) as e:
            # Log would require passing logger; skip invalid files
            continue
    return items


def write_resources(
    resource_type: str,
    items: list,
    output_dir: str,
    *,
    name_key: str = "name",
    file_extension: str = ".json",
) -> None:
    """
    Write each item (dict) to a JSON file under output_dir / resource_type.
    Filename is derived from item[name_key] + file_extension.
    """
    safe_type = resource_type.replace(" ", "_").replace("(", "").replace(")", "").lower()
    resource_dir = os.path.join(output_dir, safe_type)
    os.makedirs(resource_dir, exist_ok=True)

    for item in items:
        if not isinstance(item, dict):
            continue
        name = item.get(name_key)
        if not name:
            continue
        path = os.path.join(resource_dir, f"{name}{file_extension}")
        with open(path, "w") as f:
            json.dump(item, f, indent=2, sort_keys=False)
