"""JSON spec accumulator — the core of zuzu's render pipeline."""

from __future__ import annotations

import json
import os
from typing import Any

# Global component accumulator
_components: list[dict[str, Any]] = []
_app_config: dict[str, Any] | None = None
_pages: list[dict[str, Any]] = []


def _add_component(component: dict[str, Any]) -> None:
    """Add a component to the current spec."""
    _components.append(component)


def _set_app_config(config: dict[str, Any]) -> None:
    """Set the app configuration."""
    global _app_config
    _app_config = config


def _add_page(page: dict[str, Any]) -> None:
    """Add a page to the spec."""
    _pages.append(page)


def _build_spec() -> dict[str, Any]:
    """Build the final JSON spec."""
    spec: dict[str, Any] = {
        "__zuzu__": "app",
        "version": 1,
    }
    if _app_config:
        spec["app"] = _app_config
    if _pages:
        spec["pages"] = _pages
    if _components:
        spec["components"] = _components
    return spec


def show() -> None:
    """Flush the accumulated spec to output.

    In platform mode: writes to ZUZU_OUTPUT_PATH.
    In local mode: prints JSON to stdout.
    """
    spec = _build_spec()
    output_path = os.environ.get("ZUZU_OUTPUT_PATH")

    if output_path:
        with open(output_path, "w") as f:
            json.dump(spec, f, ensure_ascii=False)
    else:
        print(json.dumps(spec, indent=2, ensure_ascii=False))


def _reset() -> None:
    """Reset the spec accumulator. Used in tests."""
    global _app_config
    _components.clear()
    _pages.clear()
    _app_config = None
