"""Read the running Resolve application, current project and current timeline.

Run with the Python interpreter supported by your installed Scripting README.
Uses only the standard library and Blackmagic's installed DaVinciResolveScript.
No project-changing API calls, application launch, downloads or retries.
"""

import contextlib
import importlib
import importlib.util
import json
import os
from pathlib import Path
import platform
import struct
import sys


class ProbeError(RuntimeError):
    def __init__(self, exit_code, stage, message):
        super().__init__(message)
        self.exit_code = exit_code
        self.stage = stage


def load_api(checks):
    """Separate discovery, an explicit library path, and module loading."""
    checks["python_version"] = platform.python_version()
    checks["python_executable"] = sys.executable
    checks["pointer_bits"] = struct.calcsize("P") * 8
    checks["machine"] = platform.machine()
    if sys.version_info < (3, 8) or checks["pointer_bits"] != 64:
        raise ProbeError(10, "environment", "This example needs compatible 64-bit Python 3.8+.")

    loaded = sys.modules.get("DaVinciResolveScript")
    if loaded is not None:
        checks["module_origin"] = getattr(loaded, "__file__", "already_loaded")
    else:
        try:
            spec = importlib.util.find_spec("DaVinciResolveScript")
        except Exception as exc:
            raise ProbeError(10, "module_discovery", "Cannot discover the installed module.") from exc
        if spec is None:
            raise ProbeError(10, "module_discovery", "Module not found; check the interpreter and SDK Modules path.")
        checks["module_origin"] = spec.origin
    checks["module_found"] = True

    library = os.environ.get("RESOLVE_SCRIPT_LIB")
    if library is not None:
        try:
            valid = bool(library) and library == library.strip()
            valid = valid and Path(library).is_absolute() and Path(library).is_file()
        except (OSError, ValueError) as exc:
            raise ProbeError(11, "library_path", "Cannot inspect RESOLVE_SCRIPT_LIB.") from exc
        if not valid:
            raise ProbeError(11, "library_path", "RESOLVE_SCRIPT_LIB must name an existing absolute library file.")
        checks["library_path"] = "configured_file_found"
    else:
        checks["library_path"] = "managed_by_installed_module"

    try:
        api = importlib.import_module("DaVinciResolveScript")
        if not callable(getattr(api, "scriptapp", None)):
            raise TypeError("The loaded module has no callable scriptapp")
    except Exception as exc:
        raise ProbeError(12, "module_load", "Module found, but wrapper/native loading failed; inspect the cause.") from exc
    checks["module_loaded"] = True
    return api


def read_call(owner, method, stage, exit_code, *args):
    try:
        return getattr(owner, method)(*args)
    except Exception as exc:
        raise ProbeError(exit_code, stage, method + " failed.") from exc


def read_text(owner, method, stage, exit_code):
    value = read_call(owner, method, stage, exit_code)
    if not isinstance(value, str) or not value.strip():
        raise ProbeError(exit_code, stage, method + " did not return a non-empty string.")
    return value


def inspect_resolve(api):
    """All Resolve calls in this example are here; none changes a project."""
    resolve = read_call(api, "scriptapp", "connection", 20, "Resolve")
    if resolve is None:
        raise ProbeError(20, "connection", "No Resolve object; check running Studio and Local scripting access.")

    result = {
        "status": "read_access_available",
        "stage": "complete",
        "product": read_text(resolve, "GetProductName", "application_identity", 21),
        "version": read_text(resolve, "GetVersionString", "application_identity", 21),
        "project_open": False,
        "project_name": None,
        "timeline_checked": False,
        "timeline_open": False,
        "timeline_name": None,
    }
    manager = read_call(resolve, "GetProjectManager", "project_manager", 30)
    if manager is None:
        raise ProbeError(30, "project_manager", "Resolve connected, but ProjectManager is unavailable.")

    project = read_call(manager, "GetCurrentProject", "current_project", 31)
    if project is None:
        return result
    result["project_open"] = True
    result["project_name"] = read_text(project, "GetName", "current_project", 31)

    timeline = read_call(project, "GetCurrentTimeline", "current_timeline", 32)
    result["timeline_checked"] = True
    if timeline is not None:
        result["timeline_open"] = True
        result["timeline_name"] = read_text(timeline, "GetName", "current_timeline", 32)
    return result


def main():
    checks = {}
    try:
        # Keep ordinary Python messages from the installed wrapper off JSON stdout.
        with contextlib.redirect_stdout(sys.stderr):
            api = load_api(checks)
            result = inspect_resolve(api)
        code = 0
    except ProbeError as exc:
        code = exc.exit_code
        result = {"status": "failed", "stage": exc.stage, "message": str(exc)}
        if exc.__cause__ is not None:
            result["cause_type"] = type(exc.__cause__).__name__
            result["cause_message"] = str(exc.__cause__)
    result["exit_code"] = code
    result["checks"] = checks
    # ASCII escapes also work in terminals that cannot display a project's name.
    print(json.dumps(result, ensure_ascii=True, indent=2, allow_nan=False))
    return code


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