"""Utility helpers for a24wh."""

import json
from pathlib import Path
from typing import Any

from .constants import DEFAULT_JSON_FILE_TITLE, ERR_SAVE_JSON_INVALID_DATA


def save_json(response_data: dict[str, Any], file_title: str | None = None) -> str:
    """Save response data to a JSON file and return the saved file path."""

    if not isinstance(response_data, dict):
        raise TypeError(ERR_SAVE_JSON_INVALID_DATA)

    title = (file_title or "").strip()
    if not title:
        title = DEFAULT_JSON_FILE_TITLE

    file_name = title if title.lower().endswith(".json") else f"{title}.json"
    target_path = Path.cwd() / file_name

    with target_path.open("w", encoding="utf-8") as file_obj:
        json.dump(response_data, file_obj, ensure_ascii=False, indent=2)

    return str(target_path)
