"""Expose effect and offline-render helpers for the local MCP bridge."""

import os
from pathlib import Path

from mcp_export_patches import patch_offline_renderer_global


root = Path(os.environ.get("OPENDAW_AGENT_ROOT", r"D:\OpenDAW-Studio-Agent"))
static_dir = Path(os.environ.get("OPENDAW_STATIC_DIR", str(root / "opendaw-static")))
bundles = sorted(static_dir.glob("main.*.js"))
if not bundles:
    raise SystemExit(f"Could not find the OpenDAW main JavaScript bundle in {static_dir}.")

marker = "// Patch: expose EffectFactories for MCP"
namespace_end = "})(EffectFactories || (EffectFactories = {}));"
exposure = (
    namespace_end
    + "\n"
    + marker
    + "\n(() => { try { const od = window.opendaw = window.opendaw || {}; od.EffectFactories = EffectFactories; } catch (e) {} })();"
)

for bundle in bundles:
    source = bundle.read_text(encoding="utf-8")
    changed = False
    if marker not in source:
        if namespace_end not in source or "EffectFactories.AudioNamed" not in source:
            raise SystemExit(f"OpenDAW effect registry marker was not found in {bundle}.")
        source = source.replace(namespace_end, exposure, 1)
        changed = True
        print(f"[mcp] Exposed the effect factory registry in {bundle}")
    else:
        print(f"[mcp] EffectFactories already exposed in {bundle}")

    try:
        source, renderer_changed = patch_offline_renderer_global(source)
    except RuntimeError as exc:
        raise SystemExit(str(exc)) from exc
    if renderer_changed:
        changed = True
        print(f"[mcp] Exposed OfflineEngineRenderer, Option, and WavFile in {bundle}")
    else:
        print(f"[mcp] Renderer globals already exposed in {bundle}")

    if changed:
        bundle.write_text(source, encoding="utf-8")
