"""Persistent random installation identifier for operational diagnostics.

This UUID is generated by the Add-on. It is not derived from hardware,
operating-system account data, or a Blender file.
"""

import json
from pathlib import Path
import uuid

import bpy


FILE_NAME = "3dripper-helper-installation.json"


def get_installation_id():
    target = _installation_file()
    current = _read_installation_id(target)
    if current:
        return current

    installation_id = str(uuid.uuid4())
    target.parent.mkdir(parents=True, exist_ok=True)
    temporary = target.with_suffix(".tmp")
    temporary.write_text(
        json.dumps({"installationId": installation_id}, separators=(",", ":")),
        encoding="utf-8",
    )
    temporary.replace(target)
    return installation_id


def _installation_file():
    config_root = bpy.utils.user_resource("CONFIG", create=True)
    if not config_root:
        raise RuntimeError("Blender did not provide a writable configuration directory.")
    return Path(config_root) / FILE_NAME


def _read_installation_id(path):
    try:
        payload = json.loads(path.read_text(encoding="utf-8"))
        value = str(payload.get("installationId") or "")
        return str(uuid.UUID(value)) if value == str(uuid.UUID(value)) else None
    except (OSError, ValueError, TypeError, json.JSONDecodeError):
        return None
