"""LANDR Mastering Pro — live processing matches stax-master file render."""
from __future__ import annotations

import subprocess
import sys
import threading
from pathlib import Path
from typing import Any, Optional

import numpy as np

STAX = Path.home() / "JJ-PROJECTS" / "stax-master"


class ProSlot:
    def __init__(self) -> None:
        self.plug: Any = None
        self.status: str = "Twin pedalboard"
        self._lock = threading.Lock()
        self._load()

    def _ensure_path(self) -> None:
        s = str(STAX)
        if s not in sys.path:
            sys.path.insert(0, s)

    def _load(self) -> None:
        self._ensure_path()
        from pro_slot import load_pro

        plug, banner = load_pro()
        self.plug = plug
        if plug is not None:
            self.status = "LANDR Mastering Pro"
        elif "not installed" in banner.lower():
            self.status = "Twin — Pro not installed"
        else:
            self.status = "Twin — Pro unavailable"

    def using_pro(self) -> bool:
        return self.plug is not None

    def process(self, block: np.ndarray, sr: float) -> Optional[np.ndarray]:
        if self.plug is None:
            return None
        with self._lock:
            try:
                x = np.ascontiguousarray(block.T, dtype=np.float32)
                y = self.plug(x, float(sr))
                y = np.asarray(y, dtype=np.float32)
                if y.ndim == 1:
                    y = np.stack([y, y], axis=0)
                y = np.nan_to_num(y, copy=False)
                return np.clip(y.T, -1.0, 1.0)
            except Exception:
                self.plug = None
                self.status = "Twin — Pro error"
                return None

    def open_editor(self) -> None:
        if self.plug is None:
            return
        self._ensure_path()
        from pro_slot import show_pro

        show_pro(self.plug)

    @staticmethod
    def notify(title: str, body: str) -> None:
        t = title.replace('"', "").replace("\\", "")[:60]
        b = body.replace('"', "").replace("\\", "")[:180]
        subprocess.run(
            ["/usr/bin/osascript", "-e", f'display notification "{b}" with title "{t}"'],
            check=False,
            capture_output=True,
        )


_slot: Optional[ProSlot] = None
_slot_lock = threading.Lock()


def get_slot() -> ProSlot:
    global _slot
    with _slot_lock:
        if _slot is None:
            _slot = ProSlot()
        return _slot


def init_status() -> str:
    return get_slot().status


def mount_chain(chain: Any) -> None:
    chain.pro = get_slot()
