"""
Helpers for reading and writing ``llmpm.json``.

``llmpm.json`` follows npm-style conventions:

.. code-block:: json

    {
      "name": "my-project",
      "description": "",
      "dependencies": {
        "meta-llama/Llama-3.2-3B-Instruct": "*",
        "openai/whisper-base": "*"
      }
    }

Models are listed under ``dependencies`` without version pins (``"*"``).
"""

from __future__ import annotations

import json
from pathlib import Path

from llmpm.core.context import find_llmpm_json


def read() -> dict | None:
    """Return the parsed ``llmpm.json``, or ``None`` if not found / unreadable."""
    path = find_llmpm_json()
    if path is None:
        return None
    try:
        with open(path, encoding="utf-8") as fh:
            return json.load(fh)
    except (json.JSONDecodeError, OSError):
        return None


def dependencies() -> dict[str, str]:
    """Return the ``dependencies`` dict from ``llmpm.json`` (may be empty)."""
    data = read()
    if data is None:
        return {}
    return data.get("dependencies") or {}


def add_dependency(repo_id: str) -> bool:
    """
    Add *repo_id* to ``dependencies`` in ``llmpm.json``.

    Returns ``True`` on success, ``False`` if no ``llmpm.json`` was found.
    """
    path = find_llmpm_json()
    if path is None:
        return False
    data = read() or {}
    deps: dict = data.setdefault("dependencies", {})
    deps[repo_id] = "*"
    _write(path, data)
    return True


def remove_dependency(repo_id: str) -> bool:
    """
    Remove *repo_id* from ``dependencies``.

    Returns ``True`` if it existed, ``False`` otherwise.
    """
    path = find_llmpm_json()
    if path is None:
        return False
    data = read() or {}
    deps: dict = data.get("dependencies") or {}
    existed = repo_id in deps
    deps.pop(repo_id, None)
    data["dependencies"] = deps
    _write(path, data)
    return existed


# ── private ───────────────────────────────────────────────────────────────────

def _write(path: Path, data: dict) -> None:
    with open(path, "w", encoding="utf-8") as fh:
        json.dump(data, fh, indent=2)
        fh.write("\n")
