"""Render-plan access for published versions and drafts (TZ 2.6.3)."""

from __future__ import annotations

import threading
from typing import Any

from django.conf import settings

from snapfile.core.crypto import derive_key
from snapfile.doctemplates.models import Template, TemplateVersion
from snapfile_render.compiler import compile_document
from snapfile_render.plancache import PlanCache, plan_key

_cache: PlanCache | None = None
_lock = threading.Lock()


def plan_cache() -> PlanCache:
    global _cache
    if _cache is None:
        with _lock:
            if _cache is None:
                _cache = PlanCache(
                    settings.SNAPFILE_CACHE_DIR / "plans",
                    derive_key("plan-cache"),
                    max_items=settings.SNAPFILE_PLAN_LRU_ITEMS,
                    max_mb=settings.SNAPFILE_PLAN_LRU_MB,
                )
    return _cache


def _compile(doc: dict[str, Any]) -> dict[str, Any]:
    plan, _ = compile_document(doc)
    return plan


def version_plan(version: TemplateVersion) -> tuple[dict[str, Any], str]:
    key = plan_key("version", str(version.id), version.document_hash)
    plan, source = plan_cache().get_or_compile(key, lambda: _compile(version.document))
    if version.plan_status != "ready" or version.plan_ref != key:
        version.plan_status = "ready"
        version.plan_ref = key
        version.plan_hash = key
        TemplateVersion.objects.filter(pk=version.pk).update(plan_status="ready", plan_ref=key, plan_hash=key)
    return plan, source


def draft_plan(
    template: Template, document: dict[str, Any] | None = None, doc_hash: str | None = None
) -> tuple[dict[str, Any], str]:
    doc = document if document is not None else template.draft_document
    key = plan_key("draft", str(template.id), doc_hash or template.draft_hash)
    return plan_cache().get_or_compile(key, lambda: _compile(doc))
