#!/usr/bin/env python3
"""
losey_studio_obs.py — Native OBS Studio Python Plugin & Dual-Mode Bridge for Losey Studio OBS (v1.0.0).

Works standalone with the bundled public bridge (losey_studio_bridge.py) OR in Extended Studio Mode
with any compatible local bridge exposing /api/trigger/* and /api/obs-plugin/*.

How to load inside OBS Studio:
  1. OBS -> Tools -> Scripts -> Python Settings -> select your Python 3.12 folder.
  2. Click '+' -> select losey_studio_obs.py.
  3. Set your Streamer @Handle, click 'Auto-Add Studio Overlays to Current Scene',
     and bind hotkeys under OBS Settings -> Hotkeys -> search "Losey Studio".
"""

from __future__ import annotations

import argparse
import json
import os
from pathlib import Path
import queue
import shutil
import subprocess
import sys
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
import webbrowser

try:
    import obspython as obs  # type: ignore
    IN_OBS = True
except ImportError:
    obs = None
    IN_OBS = False


PLUGIN_VERSION = "1.0.0-beta.1"
DEFAULT_USER_HANDLE = "@YourHandle"
DEFAULT_BRIDGE_URL = "http://127.0.0.1:8798"
DEFAULT_PAIRING_KEY = "LOSEY-STUDIO-FREE"
DEFAULT_OUTPUT_DIR = str(Path.home() / "Videos" / "LoseyStudio")
DEFAULT_OVERLAY_SOURCE = "Losey Studio Master Overlay"
DEFAULT_BRB_SOURCE = "Losey Studio BRB Reels"

_STATE = {
    "user_handle": DEFAULT_USER_HANDLE,
    "bridge_url": DEFAULT_BRIDGE_URL,
    "pairing_key": DEFAULT_PAIRING_KEY,
    "output_dir": DEFAULT_OUTPUT_DIR,
    "auto_start_bridge": True,
    "auto_vertical_short": True,
    "overlay_source_name": DEFAULT_OVERLAY_SOURCE,
    "brb_source_name": DEFAULT_BRB_SOURCE,
    "pending_duration_hint": 45,
}

_HOTKEY_IDS: dict[str, int] = {}
_CMD_QUEUE: "queue.Queue[dict]" = queue.Queue()
_STOP_EVENT = threading.Event()
_WORKER_STARTED = False
_TIMER_REGISTERED = False
_BRIDGE_PROC: subprocess.Popen | None = None
_LAST_HEARTBEAT_CACHE: dict = {}

HOTKEY_SPECS = [
    ("losey_hk_smart_capture", "Losey Studio: Smart Capture (16:9 Wide + 9:16 Short + 1080p Pic)", "spot_and_pin"),
    ("losey_hk_record_that", "Losey Studio: Instant 15s Vertical Short + Pic", "record_that_wiki"),
    ("losey_hk_clip_pair", "Losey Studio: Quick Clip ±1 Min (16:9 + 9:16)", "make_clip_pair"),
    ("losey_hk_screenshot", "Losey Studio: Grab 1080p Screenshot", "screenshot"),
    ("losey_hk_toggle_brb", "Losey Studio: Toggle BRB Highlight Reels / Live", "mode_brb"),
    ("losey_hk_replay_60s", "Losey Studio: 60s Instant Replay PiP (16:9)", "instant_replay_60s"),
    ("losey_hk_replay_short", "Losey Studio: Play Latest Short PiP (9:16)", "replay_latest_short"),
    ("losey_hk_toggle_overlay", "Losey Studio: Toggle Master Overlay", "toggle_overlay"),
    ("losey_hk_hard_mute", "Losey Studio: Emergency Privacy Mute All Mics", "win_hard_mic_mute"),
]


def _obs_log(msg: str, level: str = "info") -> None:
    line = f"[LoseyStudioOBS] {msg}"
    if IN_OBS and obs is not None:
        try:
            lvl = obs.LOG_WARNING if level == "warn" else (obs.LOG_ERROR if level == "error" else obs.LOG_INFO)
            obs.script_log(lvl, line)
            return
        except Exception:
            pass
    print(line, flush=True)


def _clean_bridge_url(raw: str) -> str:
    val = str(raw or DEFAULT_BRIDGE_URL).strip().rstrip("/")
    if not val.startswith(("http://", "https://")):
        val = "http://" + val
    return val


def _clean_handle(raw: str) -> str:
    val = str(raw or DEFAULT_USER_HANDLE).strip()
    if not val:
        return DEFAULT_USER_HANDLE
    return val if val.startswith("@") else f"@{val}"


def _http_json(url: str, method: str = "GET", payload: dict | None = None, timeout: float = 4.0) -> dict:
    data_bytes = json.dumps(payload).encode("utf-8") if payload is not None else None
    headers = {"Content-Type": "application/json"} if payload is not None else {}
    req = urllib.request.Request(url, data=data_bytes, headers=headers, method=method)
    with urllib.request.urlopen(req, timeout=timeout) as resp:
        raw = resp.read().decode("utf-8", errors="replace").strip()
        return json.loads(raw) if raw else {"ok": True}


def _find_pythonw_executable() -> str | None:
    """Resolve real Python executable even when running embedded inside obs64.exe."""
    candidates: list[Path] = []
    for base in [getattr(sys, "prefix", ""), getattr(sys, "base_prefix", ""), os.environ.get("PYTHONHOME", "")]:
        if base:
            bp = Path(base)
            candidates.extend([bp / "pythonw.exe", bp / "python.exe"])

    exe = Path(sys.executable)
    if "python" in exe.name.lower():
        candidates.extend([exe.with_name("pythonw.exe"), exe])

    for name in ("pythonw", "python"):
        found = shutil.which(name)
        if found:
            candidates.append(Path(found))

    if os.name == "nt":
        local_app = os.environ.get("LOCALAPPDATA", "")
        prog_files = os.environ.get("ProgramFiles", r"C:\Program Files")
        for ver in ("Python312", "Python313", "Python311"):
            if local_app:
                candidates.append(Path(local_app) / "Programs" / "Python" / ver / "pythonw.exe")
                candidates.append(Path(local_app) / "Programs" / "Python" / ver / "python.exe")
            candidates.append(Path(prog_files) / ver / "pythonw.exe")

    for cand in candidates:
        try:
            if cand.is_file() and "obs" not in cand.name.lower():
                return str(cand)
        except Exception:
            pass
    return None


def _ensure_local_bridge_running() -> None:
    """If configured bridge_url points locally and is offline, launch bundled losey_studio_bridge.py silently."""
    global _BRIDGE_PROC
    if not _STATE.get("auto_start_bridge"):
        return

    base = _clean_bridge_url(_STATE["bridge_url"])
    parsed = urllib.parse.urlparse(base)
    host = (parsed.hostname or "127.0.0.1").lower()
    port = parsed.port or (443 if parsed.scheme == "https" else 8798)
    if host not in ("127.0.0.1", "localhost"):
        return

    try:
        res = _http_json(f"{base}/api/studio-profile", timeout=1.5)
        if res.get("ok"):
            return
    except Exception:
        pass

    bridge_py = Path(__file__).resolve().parent / "losey_studio_bridge.py"
    if not bridge_py.is_file():
        return

    py_exe = _find_pythonw_executable()
    if not py_exe:
        _obs_log("Could not locate pythonw.exe to auto-start losey_studio_bridge.py.", level="warn")
        return

    data_dir = str(_STATE.get("output_dir") or DEFAULT_OUTPUT_DIR)
    creationflags = getattr(subprocess, "CREATE_NO_WINDOW", 0x08000000) if os.name == "nt" else 0
    try:
        _BRIDGE_PROC = subprocess.Popen(
            [py_exe, str(bridge_py), "--host", "127.0.0.1", "--port", str(port), "--data-dir", data_dir],
            cwd=str(bridge_py.parent),
            creationflags=creationflags,
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
        )
        _obs_log(f"Auto-started local studio bridge on :{port} (PID {_BRIDGE_PROC.pid}).")
    except Exception as exc:
        _obs_log(f"Failed to auto-start bridge: {exc}", level="warn")


def trigger_bridge_action(
    action: str,
    bridge_url: str | None = None,
    user_handle: str | None = None,
    pairing_key: str | None = None,
    timeout: float = 6.0,
) -> dict:
    base = _clean_bridge_url(bridge_url or _STATE["bridge_url"])
    handle = _clean_handle(user_handle or _STATE["user_handle"])
    pkey = str(pairing_key or _STATE["pairing_key"] or DEFAULT_PAIRING_KEY).strip()
    clean_act = urllib.parse.quote(str(action or "").strip().lower(), safe="")
    url = f"{base}/api/trigger/{clean_act}"
    payload = {
        "action": action,
        "user": handle,
        "pairingKey": pkey,
        "source": "obs_python_plugin",
    }
    try:
        parsed = _http_json(url, method="POST", payload=payload, timeout=timeout)
        _obs_log(f"Triggered '{action}' for {handle} -> ok={parsed.get('ok')}")
        return parsed
    except Exception as exc:
        _obs_log(f"Trigger '{action}' failed ({url}): {exc}", level="warn")
        return {"ok": False, "action": action, "error": str(exc)}


def _trigger_async(action: str) -> None:
    if action == "record_that_wiki":
        _STATE["pending_duration_hint"] = 15
    elif action == "make_clip_pair":
        _STATE["pending_duration_hint"] = 60
    elif action == "spot_and_pin":
        _STATE["pending_duration_hint"] = 45
    threading.Thread(target=trigger_bridge_action, args=(action,), daemon=True).start()


def _sync_profile_to_bridge() -> None:
    base = _clean_bridge_url(_STATE["bridge_url"])
    handle = _clean_handle(_STATE["user_handle"])
    payload = {
        "user": handle,
        "handle": handle,
        "bridgeUrl": base,
        "pairingKey": _STATE["pairing_key"],
        "outputDir": _STATE["output_dir"],
        "autoShareShorts": bool(_STATE["auto_vertical_short"]),
        "autoVerticalShort": bool(_STATE["auto_vertical_short"]),
        "pluginVersion": PLUGIN_VERSION,
    }
    try:
        _http_json(f"{base}/api/studio-profile", method="POST", payload=payload, timeout=2.5)
    except Exception:
        pass


# --- Native OBS Main-Thread Helpers ---

def _collect_obs_live_snapshot() -> dict:
    snap = {
        "pluginVersion": PLUGIN_VERSION,
        "handle": _clean_handle(_STATE["user_handle"]),
        "currentScene": "",
        "scenes": [],
        "streaming": False,
        "recording": False,
        "replayBufferActive": False,
        "brbVisible": False,
        "overlayVisible": False,
        "micMuted": False,
    }
    if not IN_OBS or obs is None:
        return snap

    try:
        snap["streaming"] = bool(obs.obs_frontend_streaming_active())
        snap["recording"] = bool(obs.obs_frontend_recording_active())
        snap["replayBufferActive"] = bool(obs.obs_frontend_replay_buffer_active())
    except Exception:
        pass

    scene_names: list[str] = []
    scenes = None
    try:
        scenes = obs.obs_frontend_get_scenes()
        if scenes:
            for s in scenes:
                nm = obs.obs_source_get_name(s)
                if nm:
                    scene_names.append(nm)
    except Exception:
        pass
    finally:
        if scenes is not None:
            try:
                obs.source_list_release(scenes)
            except Exception:
                pass
    snap["scenes"] = scene_names

    cur_src = None
    try:
        cur_src = obs.obs_frontend_get_current_scene()
        if cur_src:
            snap["currentScene"] = obs.obs_source_get_name(cur_src) or ""
            scene = obs.obs_scene_from_source(cur_src)
            if scene:
                brb_item = obs.obs_scene_find_source_recursive(scene, _STATE["brb_source_name"])
                if brb_item:
                    snap["brbVisible"] = bool(obs.obs_sceneitem_visible(brb_item))
                ov_item = obs.obs_scene_find_source_recursive(scene, _STATE["overlay_source_name"])
                if ov_item:
                    snap["overlayVisible"] = bool(obs.obs_sceneitem_visible(ov_item))
    except Exception:
        pass
    finally:
        if cur_src is not None:
            obs.obs_source_release(cur_src)

    # Check if input/mic sources are muted
    srcs = None
    try:
        srcs = obs.obs_enum_sources()
        mic_states = []
        if srcs:
            for s in srcs:
                sid = obs.obs_source_get_unversioned_id(s) or ""
                if sid in ("wasapi_input_capture", "pulse_input_capture", "coreaudio_input_capture"):
                    mic_states.append(bool(obs.obs_source_muted(s)))
        if mic_states:
            snap["micMuted"] = all(mic_states)
    except Exception:
        pass
    finally:
        if srcs is not None:
            try:
                obs.source_list_release(srcs)
            except Exception:
                pass

    return snap


def _ensure_browser_source_in_current_scene(source_name: str, url: str, default_visible: bool = True) -> bool:
    if not IN_OBS or obs is None:
        return False
    cur_src = obs.obs_frontend_get_current_scene()
    if not cur_src:
        return False
    try:
        scene = obs.obs_scene_from_source(cur_src)
        if not scene:
            return False

        existing_src = obs.obs_get_source_by_name(source_name)
        if existing_src is None:
            settings = obs.obs_data_create()
            obs.obs_data_set_string(settings, "url", url)
            obs.obs_data_set_int(settings, "width", 1920)
            obs.obs_data_set_int(settings, "height", 1080)
            obs.obs_data_set_bool(settings, "shutdown", False)
            obs.obs_data_set_bool(settings, "restart_when_active", False)
            existing_src = obs.obs_source_create("browser_source", source_name, settings, None)
            obs.obs_data_release(settings)
            if existing_src is None:
                return False
            item = obs.obs_scene_add(scene, existing_src)
            if item is not None:
                obs.obs_sceneitem_set_visible(item, default_visible)
            obs.obs_source_release(existing_src)
            _obs_log(f"Added OBS Browser Source '{source_name}' -> {url}")
            return True
        else:
            try:
                settings = obs.obs_source_get_settings(existing_src)
                if settings:
                    obs.obs_data_set_string(settings, "url", url)
                    obs.obs_data_set_int(settings, "width", 1920)
                    obs.obs_data_set_int(settings, "height", 1080)
                    obs.obs_source_update(existing_src, settings)
                    obs.obs_data_release(settings)
                item = obs.obs_scene_find_source_recursive(scene, source_name)
                if item is None:
                    item = obs.obs_scene_add(scene, existing_src)
                    if item is not None:
                        obs.obs_sceneitem_set_visible(item, default_visible)
            finally:
                obs.obs_source_release(existing_src)
            return True
    finally:
        obs.obs_source_release(cur_src)


def _auto_add_studio_overlays() -> None:
    base = _clean_bridge_url(_STATE["bridge_url"])
    _ensure_browser_source_in_current_scene(_STATE["overlay_source_name"], f"{base}/overlay/master.html", default_visible=True)
    _ensure_browser_source_in_current_scene(_STATE["brb_source_name"], f"{base}/overlay/brb.html", default_visible=False)


def _set_scene_item_visibility(source_name: str, visible: bool | None = None) -> None:
    if not IN_OBS or obs is None:
        return
    cur_src = obs.obs_frontend_get_current_scene()
    if not cur_src:
        return
    try:
        scene = obs.obs_scene_from_source(cur_src)
        if not scene:
            return
        item = obs.obs_scene_find_source_recursive(scene, source_name)
        if not item:
            return
        target_vis = (not obs.obs_sceneitem_visible(item)) if visible is None else bool(visible)
        obs.obs_sceneitem_set_visible(item, target_vis)
    finally:
        obs.obs_source_release(cur_src)


def _switch_obs_scene(scene_name: str) -> None:
    if not IN_OBS or obs is None or not scene_name:
        return
    scenes = obs.obs_frontend_get_scenes()
    if not scenes:
        return
    try:
        for s in scenes:
            if (obs.obs_source_get_name(s) or "").lower() == scene_name.lower():
                obs.obs_frontend_set_current_scene(s)
                return
    finally:
        obs.source_list_release(scenes)


def _set_mics_muted(muted: bool | None = None) -> None:
    if not IN_OBS or obs is None:
        return
    srcs = obs.obs_enum_sources()
    if not srcs:
        return
    try:
        mics = []
        for s in srcs:
            sid = obs.obs_source_get_unversioned_id(s) or ""
            if sid in ("wasapi_input_capture", "pulse_input_capture", "coreaudio_input_capture"):
                mics.append(s)
        if not mics:
            return
        target_mute = (not all(obs.obs_source_muted(m) for m in mics)) if muted is None else bool(muted)
        for m in mics:
            obs.obs_source_set_muted(m, target_mute)
        _obs_log(f"Studio mic sources muted={target_mute}")
    finally:
        obs.source_list_release(srcs)


def _execute_obs_command(cmd_obj: dict) -> None:
    if not IN_OBS or obs is None:
        return
    cmd = str(cmd_obj.get("cmd") or "").strip().lower()
    if not cmd:
        return

    if cmd == "save_replay":
        if "durationHint" in cmd_obj:
            try:
                _STATE["pending_duration_hint"] = int(cmd_obj["durationHint"])
            except Exception:
                pass
        if not obs.obs_frontend_replay_buffer_active():
            obs.obs_frontend_replay_buffer_start()
            _obs_log("Started OBS Replay Buffer automatically before save_replay.", level="warn")
        else:
            obs.obs_frontend_replay_buffer_save()
            _obs_log("Requested OBS Replay Buffer save.")
    elif cmd == "start_replay_buffer":
        if not obs.obs_frontend_replay_buffer_active():
            obs.obs_frontend_replay_buffer_start()
    elif cmd == "screenshot":
        try:
            obs.obs_frontend_take_screenshot()
        except Exception as exc:
            _obs_log(f"obs_frontend_take_screenshot error: {exc}", level="warn")
    elif cmd == "toggle_brb":
        _set_scene_item_visibility(_STATE["brb_source_name"], None)
    elif cmd == "set_brb":
        _set_scene_item_visibility(_STATE["brb_source_name"], bool(cmd_obj.get("visible", True)))
    elif cmd == "toggle_overlay":
        _set_scene_item_visibility(_STATE["overlay_source_name"], None)
    elif cmd == "set_scene":
        _switch_obs_scene(str(cmd_obj.get("scene") or ""))
    elif cmd == "toggle_mute":
        _set_mics_muted(None)
    elif cmd == "set_mute":
        _set_mics_muted(bool(cmd_obj.get("muted", True)))
    elif cmd == "build_overlays":
        _auto_add_studio_overlays()


def _drain_obs_commands() -> None:
    """OBS main-thread timer callback (runs every 400ms)."""
    global _LAST_HEARTBEAT_CACHE
    if not IN_OBS or obs is None or _STOP_EVENT.is_set():
        return
    _LAST_HEARTBEAT_CACHE = _collect_obs_live_snapshot()
    for _ in range(12):
        try:
            item = _CMD_QUEUE.get_nowait()
        except queue.Empty:
            break
        try:
            _execute_obs_command(item)
        except Exception as exc:
            _obs_log(f"Command execution error ({item}): {exc}", level="warn")


def _bridge_worker_loop() -> None:
    """Background HTTP heartbeat + command poller (never blocks OBS UI thread)."""
    last_hb = 0.0
    while not _STOP_EVENT.is_set():
        base = _clean_bridge_url(_STATE["bridge_url"])
        now = time.monotonic()

        # Poll command queue every 0.45s
        try:
            res = _http_json(f"{base}/api/obs-plugin/commands", method="GET", timeout=2.0)
            for c in res.get("commands") or []:
                if isinstance(c, dict):
                    _CMD_QUEUE.put(c)
        except Exception:
            pass

        # Send OBS heartbeat every 2.5s
        if now - last_hb >= 2.5 and _LAST_HEARTBEAT_CACHE:
            last_hb = now
            try:
                _http_json(f"{base}/api/obs-plugin/heartbeat", method="POST", payload=_LAST_HEARTBEAT_CACHE, timeout=2.0)
            except Exception:
                pass

        _STOP_EVENT.wait(0.45)


def _post_replay_saved(replay_path: str, duration_hint: int) -> None:
    base = _clean_bridge_url(_STATE["bridge_url"])
    payload = {
        "path": replay_path,
        "user": _clean_handle(_STATE["user_handle"]),
        "makeShort": bool(_STATE["auto_vertical_short"]),
        "durationHint": int(duration_hint),
    }
    try:
        res = _http_json(f"{base}/api/obs-plugin/replay-saved", method="POST", payload=payload, timeout=5.0)
        _obs_log(f"Sent saved replay to bridge: {replay_path} -> ok={res.get('ok')}")
    except Exception as exc:
        _obs_log(f"Failed notifying bridge of saved replay: {exc}", level="warn")


def _on_frontend_event(event: int) -> None:
    if not IN_OBS or obs is None:
        return
    if event == obs.OBS_FRONTEND_EVENT_REPLAY_BUFFER_SAVED:
        try:
            last_path = obs.obs_frontend_get_last_replay() or ""
        except Exception:
            last_path = ""
        if last_path:
            dur = int(_STATE.get("pending_duration_hint") or 45)
            _STATE["pending_duration_hint"] = 45
            threading.Thread(target=_post_replay_saved, args=(last_path, dur), daemon=True).start()


def _make_hotkey_callback(action: str):
    def _cb(pressed: bool) -> None:
        if pressed:
            _trigger_async(action)
    return _cb


def _on_btn_open_remote(props, prop) -> bool:
    base = _clean_bridge_url(_STATE["bridge_url"])
    user_q = urllib.parse.quote(_clean_handle(_STATE["user_handle"]).lstrip("@"))
    webbrowser.open(f"{base}/remote?user={user_q}")
    return False


def _on_btn_add_overlays(props, prop) -> bool:
    _auto_add_studio_overlays()
    return False


def _on_btn_start_replay(props, prop) -> bool:
    if IN_OBS and obs is not None and not obs.obs_frontend_replay_buffer_active():
        obs.obs_frontend_replay_buffer_start()
    return False


def _on_btn_smart_capture(props, prop) -> bool:
    _trigger_async("spot_and_pin")
    return False


def _on_btn_record_that(props, prop) -> bool:
    _trigger_async("record_that_wiki")
    return False


def _on_btn_screenshot(props, prop) -> bool:
    _trigger_async("screenshot")
    return False


def _on_btn_toggle_brb(props, prop) -> bool:
    _trigger_async("mode_brb")
    return False


# --- OBS Studio Script Lifecycle Hooks ---

def script_description() -> str:
    return (
        f"<h2>Losey Studio OBS v{PLUGIN_VERSION}</h2>"
        "<p>Dual <b>16:9 + 9:16 Vertical Short</b> Replay Buffer clipper, per-user <b>/remote</b> dock, "
        "<b>Master Broadcast Overlays</b>, and <b>BRB Highlight Reels</b> — works for any game on OBS Studio.</p>"
        "<p><b>Quick Setup:</b> Click <i>Auto-Add Studio Overlays to Current Scene</i> below, enable OBS "
        "<b>Replay Buffer</b>, and bind hotkeys in <i>OBS Settings &rarr; Hotkeys</i> (filter <b>Losey Studio</b>).</p>"
    )


def script_defaults(settings) -> None:
    if not IN_OBS or obs is None:
        return
    obs.obs_data_set_default_string(settings, "user_handle", DEFAULT_USER_HANDLE)
    obs.obs_data_set_default_string(settings, "bridge_url", DEFAULT_BRIDGE_URL)
    obs.obs_data_set_default_string(settings, "pairing_key", DEFAULT_PAIRING_KEY)
    obs.obs_data_set_default_string(settings, "output_dir", DEFAULT_OUTPUT_DIR)
    obs.obs_data_set_default_bool(settings, "auto_start_bridge", True)
    obs.obs_data_set_default_bool(settings, "auto_vertical_short", True)
    obs.obs_data_set_default_string(settings, "overlay_source_name", DEFAULT_OVERLAY_SOURCE)
    obs.obs_data_set_default_string(settings, "brb_source_name", DEFAULT_BRB_SOURCE)


def script_properties():
    if not IN_OBS or obs is None:
        return None
    props = obs.obs_properties_create()
    obs.obs_properties_add_text(props, "user_handle", "Streamer @Handle", obs.OBS_TEXT_DEFAULT)
    obs.obs_properties_add_text(props, "bridge_url", "Local Studio Bridge URL", obs.OBS_TEXT_DEFAULT)
    obs.obs_properties_add_text(props, "pairing_key", "Studio Pairing Key", obs.OBS_TEXT_PASSWORD)
    obs.obs_properties_add_path(props, "output_dir", "Clips Output Folder", obs.OBS_PATH_DIRECTORY, "", DEFAULT_OUTPUT_DIR)
    obs.obs_properties_add_bool(props, "auto_start_bridge", "Auto-Start Local Studio Bridge (:8798)")
    obs.obs_properties_add_bool(props, "auto_vertical_short", "Auto-Render 9:16 Vertical Short on Capture")
    obs.obs_properties_add_text(props, "overlay_source_name", "Master Overlay Source Name", obs.OBS_TEXT_DEFAULT)
    obs.obs_properties_add_text(props, "brb_source_name", "BRB Reels Source Name", obs.OBS_TEXT_DEFAULT)
    obs.obs_properties_add_button(props, "btn_open_remote", "Open /remote Studio Console", _on_btn_open_remote)
    obs.obs_properties_add_button(props, "btn_add_overlays", "Auto-Add Studio Overlays to Current Scene", _on_btn_add_overlays)
    obs.obs_properties_add_button(props, "btn_start_replay", "Start Replay Buffer Now", _on_btn_start_replay)
    obs.obs_properties_add_button(props, "btn_smart_capture", "Test Smart Capture (16:9 + 9:16 + Pic)", _on_btn_smart_capture)
    obs.obs_properties_add_button(props, "btn_record_that", "Test 15s Vertical Short", _on_btn_record_that)
    obs.obs_properties_add_button(props, "btn_screenshot", "Grab 1080p Screenshot", _on_btn_screenshot)
    obs.obs_properties_add_button(props, "btn_toggle_brb", "Toggle BRB Highlight Reels", _on_btn_toggle_brb)
    return props


def script_update(settings) -> None:
    if not IN_OBS or obs is None:
        return
    _STATE["user_handle"] = _clean_handle(obs.obs_data_get_string(settings, "user_handle"))
    _STATE["bridge_url"] = _clean_bridge_url(obs.obs_data_get_string(settings, "bridge_url"))
    _STATE["pairing_key"] = str(obs.obs_data_get_string(settings, "pairing_key") or DEFAULT_PAIRING_KEY).strip()
    _STATE["output_dir"] = str(obs.obs_data_get_string(settings, "output_dir") or DEFAULT_OUTPUT_DIR).strip()
    _STATE["auto_start_bridge"] = bool(obs.obs_data_get_bool(settings, "auto_start_bridge"))
    _STATE["auto_vertical_short"] = bool(obs.obs_data_get_bool(settings, "auto_vertical_short"))
    _STATE["overlay_source_name"] = str(obs.obs_data_get_string(settings, "overlay_source_name") or DEFAULT_OVERLAY_SOURCE).strip()
    _STATE["brb_source_name"] = str(obs.obs_data_get_string(settings, "brb_source_name") or DEFAULT_BRB_SOURCE).strip()
    threading.Thread(target=_sync_profile_to_bridge, daemon=True).start()


def script_load(settings) -> None:
    global _WORKER_STARTED, _TIMER_REGISTERED
    if not IN_OBS or obs is None:
        return
    _STOP_EVENT.clear()
    script_update(settings)

    for hk_id, label, action in HOTKEY_SPECS:
        cb = _make_hotkey_callback(action)
        hid = obs.obs_hotkey_register_frontend(hk_id, label, cb)
        arr = obs.obs_data_get_array(settings, hk_id)
        obs.obs_hotkey_load(hid, arr)
        obs.obs_data_array_release(arr)
        _HOTKEY_IDS[hk_id] = hid

    obs.obs_frontend_add_event_callback(_on_frontend_event)
    threading.Thread(target=_ensure_local_bridge_running, daemon=True).start()

    if not _TIMER_REGISTERED:
        obs.timer_add(_drain_obs_commands, 400)
        _TIMER_REGISTERED = True

    if not _WORKER_STARTED:
        _WORKER_STARTED = True
        threading.Thread(target=_bridge_worker_loop, daemon=True).start()

    _obs_log(f"Loaded v{PLUGIN_VERSION} with {len(_HOTKEY_IDS)} hotkeys for {_STATE['user_handle']}.")


def script_save(settings) -> None:
    if not IN_OBS or obs is None:
        return
    for hk_id, hid in _HOTKEY_IDS.items():
        arr = obs.obs_hotkey_save(hid)
        obs.obs_data_set_array(settings, hk_id, arr)
        obs.obs_data_array_release(arr)


def script_unload() -> None:
    global _TIMER_REGISTERED, _WORKER_STARTED
    _STOP_EVENT.set()
    if IN_OBS and obs is not None and _TIMER_REGISTERED:
        try:
            obs.timer_remove(_drain_obs_commands)
        except Exception:
            pass
    _TIMER_REGISTERED = False
    _WORKER_STARTED = False


# --- Standalone CLI Entrypoint ---

def _cli_main() -> int:
    parser = argparse.ArgumentParser(description=f"Losey Studio OBS Plugin v{PLUGIN_VERSION} CLI")
    parser.add_argument("--bridge", default=DEFAULT_BRIDGE_URL, help="Local studio bridge base URL")
    parser.add_argument("--user", default=DEFAULT_USER_HANDLE, help="Streamer @handle")
    parser.add_argument("--pairing-key", default=DEFAULT_PAIRING_KEY, help="Studio pairing key")
    parser.add_argument("--trigger", help="Action slug to trigger (e.g. spot_and_pin, record_that_wiki, screenshot)")
    parser.add_argument("--status", action="store_true", help="Check bridge status and active profile")
    parser.add_argument("--selftest", action="store_true", help="Run offline sanity checks on plugin definitions")
    args = parser.parse_args()

    if args.selftest:
        print(json.dumps({
            "ok": True,
            "version": PLUGIN_VERSION,
            "hotkeysCount": len(HOTKEY_SPECS),
            "pythonExeDetected": _find_pythonw_executable(),
            "inObs": IN_OBS,
        }, indent=2))
        return 0

    base = _clean_bridge_url(args.bridge)
    handle = _clean_handle(args.user)

    if args.trigger:
        res = trigger_bridge_action(args.trigger, bridge_url=base, user_handle=handle, pairing_key=args.pairing_key)
        print(json.dumps(res, indent=2))
        return 0 if res.get("ok") else 1

    if args.status:
        user_q = urllib.parse.quote(handle.lstrip("@"))
        try:
            res = _http_json(f"{base}/api/studio-profile?user={user_q}", timeout=3.0)
            print(json.dumps(res, indent=2))
            return 0 if res.get("ok") else 1
        except Exception as exc:
            print(json.dumps({"ok": False, "error": str(exc)}, indent=2))
            return 1

    parser.print_help()
    return 0


if __name__ == "__main__":
    raise SystemExit(_cli_main())
