"""Auto-enable the MCP for Blender addon's asset-library integrations.

Placed in Blender's scripts/startup/, so it runs on every launch.

Which integrations are covered:
  - Poly Haven  (CC0 HDRIs / textures / models, no API key needed)
  - Poly Pizza  (CC0 / CC-BY low-poly models, needs an API key)
  - Sketchfab   (mixed-licence model catalogue, needs an API token)

Why this is needed: the MCP for Blender addon stores its integration switches as
*scene* properties (blendermcp_use_polyhaven, ...). Those reset to their default
(False) on every new file, which silently turns the asset library back off.

The API keys themselves are NOT stored here. They live in the addon's
preferences (BLENDERMCP_AddonPreferences -> polypizza_api_key / sketchfab_api_key),
which are saved into userpref.blend and therefore survive both file loads and
restarts. This script only flips the per-file switches.

Why it is not a one-liner: startup scripts run BEFORE the addon is enabled, so
the Scene property does not exist yet at that point, and `bpy.context.scene` can
still be None. The addon therefore cannot be patched at script-load time. This
script instead polls with a timer until the property becomes available, and
re-arms itself after every file load.

Add more flags to FORCE_ON below as integrations become available.
"""

import bpy

# Scene property -> value that should be forced on.
FORCE_ON = {
    "blendermcp_use_polyhaven": True,
    "blendermcp_use_polypizza": True,
    "blendermcp_use_sketchfab": True,
}


def _apply_to_scene(scene):
    """Apply FORCE_ON to a scene. Returns True if any property was settable."""
    if scene is None:
        return False
    touched = False
    for prop, value in FORCE_ON.items():
        if not hasattr(type(scene), prop):
            continue  # addon has not registered this property yet
        try:
            if getattr(scene, prop) != value:
                setattr(scene, prop, value)
            touched = True
        except (AttributeError, TypeError, RuntimeError):
            pass
    return touched


def _apply_to_context():
    return _apply_to_scene(getattr(bpy.context, "scene", None))


def _poll():
    """One-shot timer: apply once the addon has registered its properties."""
    if _apply_to_context():
        return None  # done, stop polling
    return 0.5  # not ready yet, retry


@bpy.app.handlers.persistent
def _on_load_post(*args):
    """A new file was loaded: its scene starts with the flags off again.

    Must be @persistent - Blender clears the handler lists on every file load
    unless a handler opts out. Timers are cleared on load too, so the poll is
    re-armed here.
    """
    _apply_to_context()
    bpy.app.timers.register(_poll, first_interval=0.2)


def register():
    """Arm the handler and the poll timer. Safe to call more than once."""
    if _on_load_post not in bpy.app.handlers.load_post:
        bpy.app.handlers.load_post.append(_on_load_post)
    if not bpy.app.timers.is_registered(_poll):
        bpy.app.timers.register(_poll, first_interval=1.0)


def unregister():
    """Disarm everything this script installed."""
    if _on_load_post in bpy.app.handlers.load_post:
        bpy.app.handlers.load_post.remove(_on_load_post)
    if bpy.app.timers.is_registered(_poll):
        bpy.app.timers.unregister(_poll)


# Blender 5.1 wants a registerable script to expose register()/unregister().
register()

print("Asset library auto-enable startup script loaded")
