# -*- coding: utf-8 -*-
"""Minimal Resolve-internal launcher with startup diagnostics.

Keep this file compatible with the Python 3 runtime selected by Fusion. The
actual worker remains in BaoCardCut_FreeBackendProbe.py and is executed in this
same global namespace so Resolve's injected objects stay available.
"""

import builtins
import json
import os
import sys
import time
import traceback
from pathlib import Path


def _bridge_dir():
    configured = str(os.environ.get("BAOCARDCUT_BRIDGE_DIR") or "").strip()
    if configured:
        return Path(configured)
    return (
        Path.home()
        / "Library"
        / "Application Support"
        / "BaoCardCut Free"
        / "resolve_bridge"
    )


def _append_launcher_log(path, message):
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("a", encoding="utf-8") as handle:
        handle.write(
            time.strftime("%Y-%m-%d %H:%M:%S")
            + " "
            + str(message)
            + "\n"
        )


def _write_failure_state(path, error):
    payload = {
        "ok": False,
        "stage": "python_launcher",
        "error": str(error),
        "traceback": traceback.format_exc(),
        "python_version": sys.version,
        "python_executable": sys.executable,
        "started_at": time.time(),
    }
    temporary = path.with_name(path.name + ".launcher.tmp")
    temporary.write_text(
        json.dumps(payload, ensure_ascii=False, indent=2),
        encoding="utf-8",
    )
    os.replace(str(temporary), str(path))


_STATE_DIR = _bridge_dir()
_LAUNCHER_LOG = _STATE_DIR / "free_backend_python_launcher.log"
_STATE_PATH = _STATE_DIR / "free_backend_probe_state.json"


def _worker_path():
    candidates = []
    script_text = str(globals().get("__file__") or "").strip()
    if script_text:
        candidates.append(
            Path(script_text).expanduser().resolve().parent
            / "BaoCardCut_FreeBackendProbe.py"
        )
    candidates.append(
        Path.home()
        / "Library"
        / "Application Support"
        / "Blackmagic Design"
        / "DaVinci Resolve"
        / "Fusion"
        / "Scripts"
        / "BaoCardCut_FreeBackendProbe.py"
    )
    candidates.append(Path.cwd() / "BaoCardCut_FreeBackendProbe.py")
    for candidate in candidates:
        if candidate.is_file():
            return candidate
    return candidates[0]


_WORKER_PATH = _worker_path()

try:
    _append_launcher_log(
        _LAUNCHER_LOG,
        "launcher entered python="
        + sys.version.replace("\n", " ")
        + " executable="
        + str(sys.executable)
        + " worker="
        + str(_WORKER_PATH),
    )
    _source = _WORKER_PATH.read_text(encoding="utf-8-sig")
    exec(compile(_source, str(_WORKER_PATH), "exec"), globals(), globals())
    _append_launcher_log(_LAUNCHER_LOG, "worker source accepted")
except builtins.BaseException as _launcher_error:
    try:
        _write_failure_state(_STATE_PATH, _launcher_error)
        _append_launcher_log(_LAUNCHER_LOG, "worker startup failed: " + str(_launcher_error))
    except builtins.BaseException:
        pass
    raise
