bl_info = {
    "name": "Text Driver Compatibility",
    "author": "Your Name",
    "version": (1, 0),
    "blender": (2, 80, 0),
    "location": "Object Properties > Text Driver",
    "description": "Добавляет анимируемое свойство для управления text.body через драйверы",
    "category": "Object",
}

import bpy
from bpy.app.handlers import persistent

# --- Основная логика ---
def register_properties():
    """Регистрирует кастомное свойство для объектов"""
    bpy.types.Object.text_driver_compat = bpy.props.StringProperty(
        name="Driver Text",
        description="Значение этого поля будет скопировано в body текстового объекта. Сюда можно назначать драйвер.",
        default="",
        options={'ANIMATABLE'}
    )

def unregister_properties():
    """Удаляет кастомное свойство"""
    del bpy.types.Object.text_driver_compat

@persistent
def sync_driver_to_body(scene):
    """Хендлер: копирует значение из свойства-драйвера в data.body"""
    for obj in scene.objects:
        if obj.type == 'FONT' and hasattr(obj, 'text_driver_compat'):
            # Проверяем, отличается ли строка, чтобы избежать лишних операций
            if obj.data.body != obj.text_driver_compat:
                obj.data.body = obj.text_driver_compat

# --- Интерфейс (Панель в свойствах объекта) ---
class OBJECT_PT_text_driver_panel(bpy.types.Panel):
    bl_label = "Text Driver"
    bl_idname = "OBJECT_PT_text_driver"
    bl_space_type = 'PROPERTIES'
    bl_region_type = 'WINDOW'
    bl_context = "object"

    @classmethod
    def poll(cls, context):
        # Панель видна только для текстовых объектов
        return context.object and context.object.type == 'FONT'

    def draw(self, context):
        layout = self.layout
        obj = context.object

        # Отображаем наше кастомное свойство
        layout.prop(obj, "text_driver_compat")

        # Для информации показываем текущий текст
        box = layout.box()
        box.label(text="Current Text Body:")
        for i, line in enumerate(obj.data.body.split("\n")):
            box.label(text=f"  {line}")

# --- Регистрация ---
classes = [OBJECT_PT_text_driver_panel]

def register():
    register_properties()
    for cls in classes:
        bpy.utils.register_class(cls)

    # Добавляем хендлер
    if sync_driver_to_body not in bpy.app.handlers.frame_change_post:
        bpy.app.handlers.frame_change_post.append(sync_driver_to_body)

    print("Text Driver Compatibility Add-on activated.")

def unregister():
    # Удаляем хендлер
    if sync_driver_to_body in bpy.app.handlers.frame_change_post:
        bpy.app.handlers.frame_change_post.remove(sync_driver_to_body)

    for cls in reversed(classes):
        bpy.utils.unregister_class(cls)
    unregister_properties()

    print("Text Driver Compatibility Add-on deactivated.")

if __name__ == "__main__":
    register()