# File: db/models.py
from matrx_orm import BigIntegerField, BooleanField, CharField, DateField, DateTimeField, DecimalField, EnumField, FloatField, ForeignKey, IntegerField, JSONBField, Model, SmallIntegerField, TextArrayField, TextField, UUIDField, model_registry, BaseDTO, BaseManager
from enum import Enum
from dataclasses import dataclass
from typing import ClassVar

class Users(Model):
    id = UUIDField(primary_key=True, null=False)
    email = CharField(null=False)

    _table_name = "users"
    _db_schema = "auth"
    _database = "supabase_automation_matrix"

class AiProvider(Model):
    id = UUIDField(primary_key=True, null=False)
    name = CharField()
    company_description = TextField()
    documentation_link = CharField()
    models_link = CharField()
    _inverse_foreign_keys: ClassVar[dict[str, dict[str, str]]] = {'ai_settings': {'from_model': 'AiSettings', 'from_field': 'ai_provider', 'referenced_field': 'id', 'related_name': 'ai_settings'}, 'ai_model': {'from_model': 'AiModel', 'from_field': 'model_provider', 'referenced_field': 'id', 'related_name': 'ai_model'}}
    _database = "supabase_automation_matrix"

class CxAgentMemory(Model):
    id = UUIDField(primary_key=True, null=False)
    user_id = ForeignKey(to_model=Users, to_column='id', to_schema='auth', null=False, unique=True)
    memory_type = TextField(null=False)
    scope = TextField(null=False, default='user', unique=True)
    scope_id = TextField(unique=True)
    key = TextField(null=False, unique=True)
    content = TextField(null=False)
    importance = FloatField(default=0.5)
    access_count = IntegerField(default=0)
    last_accessed_at = DateTimeField()
    expires_at = DateTimeField()
    metadata = JSONBField(null=False, default={})
    created_at = DateTimeField(null=False)
    updated_at = DateTimeField(null=False)
    deleted_at = DateTimeField()
    _inverse_foreign_keys: ClassVar[dict[str, dict[str, str]]] = {}
    _database = "supabase_automation_matrix"

class Organizations(Model):
    id = UUIDField(primary_key=True, null=False)
    name = TextField(null=False)
    slug = TextField(null=False, unique=True)
    description = TextField()
    logo_url = TextField()
    website = TextField()
    created_at = DateTimeField()
    updated_at = DateTimeField()
    created_by = ForeignKey(to_model=Users, to_column='id', to_schema='auth', )
    is_personal = BooleanField(default=False)
    settings = JSONBField(default={})
    _inverse_foreign_keys: ClassVar[dict[str, dict[str, str]]] = {'workspaces': {'from_model': 'Workspaces', 'from_field': 'organization_id', 'referenced_field': 'id', 'related_name': 'workspaces'}, 'context_variables': {'from_model': 'ContextVariables', 'from_field': 'organization_id', 'referenced_field': 'id', 'related_name': 'context_variables'}, 'permissions': {'from_model': 'Permissions', 'from_field': 'granted_to_organization_id', 'referenced_field': 'id', 'related_name': 'permissions'}, 'organization_members': {'from_model': 'OrganizationMembers', 'from_field': 'organization_id', 'referenced_field': 'id', 'related_name': 'organization_members'}, 'user_active_context': {'from_model': 'UserActiveContext', 'from_field': 'organization_id', 'referenced_field': 'id', 'related_name': 'user_active_context'}, 'broker_values': {'from_model': 'BrokerValues', 'from_field': 'organization_id', 'referenced_field': 'id', 'related_name': 'broker_values'}, 'user_files': {'from_model': 'UserFiles', 'from_field': 'organization_id', 'referenced_field': 'id', 'related_name': 'user_files'}, 'projects': {'from_model': 'Projects', 'from_field': 'organization_id', 'referenced_field': 'id', 'related_name': 'projects'}, 'organization_invitations': {'from_model': 'OrganizationInvitations', 'from_field': 'organization_id', 'referenced_field': 'id', 'related_name': 'organization_invitations'}, 'cx_conversation': {'from_model': 'CxConversation', 'from_field': 'organization_id', 'referenced_field': 'id', 'related_name': 'cx_conversation'}, 'sandbox_instances': {'from_model': 'SandboxInstances', 'from_field': 'organization_id', 'referenced_field': 'id', 'related_name': 'sandbox_instances'}, 'context_items': {'from_model': 'ContextItems', 'from_field': 'organization_id', 'referenced_field': 'id', 'related_name': 'context_items'}, 'app_instances': {'from_model': 'AppInstances', 'from_field': 'organization_id', 'referenced_field': 'id', 'related_name': 'app_instances'}, 'notes': {'from_model': 'Notes', 'from_field': 'organization_id', 'referenced_field': 'id', 'related_name': 'notes'}, 'user_tables': {'from_model': 'UserTables', 'from_field': 'organization_id', 'referenced_field': 'id', 'related_name': 'user_tables'}, 'transcripts': {'from_model': 'Transcripts', 'from_field': 'organization_id', 'referenced_field': 'id', 'related_name': 'transcripts'}, 'workflow': {'from_model': 'Workflow', 'from_field': 'organization_id', 'referenced_field': 'id', 'related_name': 'workflow'}, 'canvas_items': {'from_model': 'CanvasItems', 'from_field': 'organization_id', 'referenced_field': 'id', 'related_name': 'canvas_items'}, 'prompts': {'from_model': 'Prompts', 'from_field': 'organization_id', 'referenced_field': 'id', 'related_name': 'prompts'}}
    _database = "supabase_automation_matrix"

class ShortcutCategories(Model):
    id = UUIDField(primary_key=True, null=False)
    placement_type = TextField(null=False)
    parent_category_id = ForeignKey(to_model='ShortcutCategories', to_column='id', )
    label = TextField(null=False)
    description = TextField()
    icon_name = TextField(null=False, default='SquareMenu')
    color = TextField(default='zinc')
    sort_order = IntegerField(default=999)
    is_active = BooleanField(default=True)
    metadata = JSONBField(default={})
    enabled_contexts = JSONBField(default=['general'])
    _inverse_foreign_keys: ClassVar[dict[str, dict[str, str]]] = {'content_blocks': {'from_model': 'ContentBlocks', 'from_field': 'category_id', 'referenced_field': 'id', 'related_name': 'content_blocks'}, 'prompt_shortcuts': {'from_model': 'PromptShortcuts', 'from_field': 'category_id', 'referenced_field': 'id', 'related_name': 'prompt_shortcuts'}, 'system_prompts_new': {'from_model': 'SystemPromptsNew', 'from_field': 'category_id', 'referenced_field': 'id', 'related_name': 'system_prompts_new'}}
    _database = "supabase_automation_matrix"

class Tools(Model):
    id = UUIDField(primary_key=True, null=False)
    name = TextField(null=False, unique=True)
    description = TextField(null=False)
    parameters = JSONBField(null=False)
    output_schema = JSONBField()
    annotations = JSONBField(default=[])
    function_path = TextField(null=False)
    category = TextField()
    tags = TextArrayField()
    icon = CharField(max_length=255)
    is_active = BooleanField(default=True)
    semver = TextField(default='1.0.0')
    created_at = DateTimeField()
    updated_at = DateTimeField()
    source_app = TextField(null=False, default='matrx_ai')
    version = IntegerField(null=False, default=1)
    _inverse_foreign_keys: ClassVar[dict[str, dict[str, str]]] = {'tool_versions': {'from_model': 'ToolVersions', 'from_field': 'tool_id', 'referenced_field': 'id', 'related_name': 'tool_versions'}, 'tool_test_samples': {'from_model': 'ToolTestSamples', 'from_field': 'tool_id', 'referenced_field': 'id', 'related_name': 'tool_test_samples'}, 'tool_ui_components': {'from_model': 'ToolUiComponents', 'from_field': 'tool_id', 'referenced_field': 'id', 'related_name': 'tool_ui_components'}}
    _database = "supabase_automation_matrix"

class AiModel(Model):
    id = UUIDField(primary_key=True, null=False)
    name = CharField(null=False)
    common_name = CharField()
    model_class = CharField(null=False)
    provider = CharField()
    endpoints = JSONBField()
    context_window = BigIntegerField()
    max_tokens = BigIntegerField()
    capabilities = JSONBField()
    controls = JSONBField()
    model_provider = ForeignKey(to_model=AiProvider, to_column='id', )
    is_deprecated = BooleanField(default=False)
    is_primary = BooleanField(default=False)
    is_premium = BooleanField(default=False)
    api_class = CharField()
    _inverse_foreign_keys: ClassVar[dict[str, dict[str, str]]] = {'ai_model_endpoint': {'from_model': 'AiModelEndpoint', 'from_field': 'ai_model_id', 'referenced_field': 'id', 'related_name': 'ai_model_endpoint'}, 'recipe_model': {'from_model': 'RecipeModel', 'from_field': 'ai_model', 'referenced_field': 'id', 'related_name': 'recipe_model'}, 'ai_settings': {'from_model': 'AiSettings', 'from_field': 'ai_model', 'referenced_field': 'id', 'related_name': 'ai_settings'}, 'agent_conversations': {'from_model': 'AgentConversations', 'from_field': 'model_id', 'referenced_field': 'id', 'related_name': 'agent_conversations'}, 'agent_requests': {'from_model': 'AgentRequests', 'from_field': 'model_id', 'referenced_field': 'id', 'related_name': 'agent_requests'}, 'cx_conversation': {'from_model': 'CxConversation', 'from_field': 'last_model_id', 'referenced_field': 'id', 'related_name': 'cx_conversation'}, 'cx_request': {'from_model': 'CxRequest', 'from_field': 'ai_model_id', 'referenced_field': 'id', 'related_name': 'cx_request'}, 'prompts': {'from_model': 'Prompts', 'from_field': 'model_id', 'referenced_field': 'id', 'related_name': 'prompts'}, 'prompt_builtins': {'from_model': 'PromptBuiltins', 'from_field': 'model_id', 'referenced_field': 'id', 'related_name': 'prompt_builtins'}}
    _database = "supabase_automation_matrix"

class ContentBlocks(Model):
    id = UUIDField(primary_key=True, null=False)
    block_id = CharField(null=False, max_length=100, unique=True)
    label = CharField(null=False, max_length=255)
    description = TextField()
    icon_name = CharField(null=False, max_length=100)
    template = TextField(null=False)
    sort_order = IntegerField(default=0)
    is_active = BooleanField(default=True)
    created_at = DateTimeField()
    updated_at = DateTimeField()
    category_id = ForeignKey(to_model=ShortcutCategories, to_column='id', )
    _inverse_foreign_keys: ClassVar[dict[str, dict[str, str]]] = {}
    _database = "supabase_automation_matrix"

class Workspaces(Model):
    id = UUIDField(primary_key=True, null=False)
    organization_id = ForeignKey(to_model=Organizations, to_column='id', null=False)
    parent_workspace_id = ForeignKey(to_model='Workspaces', to_column='id', )
    name = TextField(null=False)
    description = TextField()
    settings = JSONBField(default={})
    created_at = DateTimeField()
    updated_at = DateTimeField()
    created_by = ForeignKey(to_model=Users, to_column='id', to_schema='auth', )
    _inverse_foreign_keys: ClassVar[dict[str, dict[str, str]]] = {'context_variables': {'from_model': 'ContextVariables', 'from_field': 'workspace_id', 'referenced_field': 'id', 'related_name': 'context_variables'}, 'user_active_context': {'from_model': 'UserActiveContext', 'from_field': 'workspace_id', 'referenced_field': 'id', 'related_name': 'user_active_context'}, 'broker_values': {'from_model': 'BrokerValues', 'from_field': 'workspace_id', 'referenced_field': 'id', 'related_name': 'broker_values'}, 'user_files': {'from_model': 'UserFiles', 'from_field': 'workspace_id', 'referenced_field': 'id', 'related_name': 'user_files'}, 'projects': {'from_model': 'Projects', 'from_field': 'workspace_id', 'referenced_field': 'id', 'related_name': 'projects'}, 'cx_conversation': {'from_model': 'CxConversation', 'from_field': 'workspace_id', 'referenced_field': 'id', 'related_name': 'cx_conversation'}, 'sandbox_instances': {'from_model': 'SandboxInstances', 'from_field': 'workspace_id', 'referenced_field': 'id', 'related_name': 'sandbox_instances'}, 'context_items': {'from_model': 'ContextItems', 'from_field': 'workspace_id', 'referenced_field': 'id', 'related_name': 'context_items'}, 'app_instances': {'from_model': 'AppInstances', 'from_field': 'workspace_id', 'referenced_field': 'id', 'related_name': 'app_instances'}, 'notes': {'from_model': 'Notes', 'from_field': 'workspace_id', 'referenced_field': 'id', 'related_name': 'notes'}, 'workspace_members': {'from_model': 'WorkspaceMembers', 'from_field': 'workspace_id', 'referenced_field': 'id', 'related_name': 'workspace_members'}, 'workspace_invitations': {'from_model': 'WorkspaceInvitations', 'from_field': 'workspace_id', 'referenced_field': 'id', 'related_name': 'workspace_invitations'}, 'user_tables': {'from_model': 'UserTables', 'from_field': 'workspace_id', 'referenced_field': 'id', 'related_name': 'user_tables'}, 'transcripts': {'from_model': 'Transcripts', 'from_field': 'workspace_id', 'referenced_field': 'id', 'related_name': 'transcripts'}, 'workflow': {'from_model': 'Workflow', 'from_field': 'workspace_id', 'referenced_field': 'id', 'related_name': 'workflow'}, 'canvas_items': {'from_model': 'CanvasItems', 'from_field': 'workspace_id', 'referenced_field': 'id', 'related_name': 'canvas_items'}, 'prompts': {'from_model': 'Prompts', 'from_field': 'workspace_id', 'referenced_field': 'id', 'related_name': 'prompts'}}
    _database = "supabase_automation_matrix"

class Projects(Model):
    id = UUIDField(primary_key=True, null=False)
    name = TextField(null=False)
    description = TextField()
    created_at = DateTimeField()
    updated_at = DateTimeField()
    created_by = ForeignKey(to_model=Users, to_column='id', to_schema='auth', )
    organization_id = ForeignKey(to_model=Organizations, to_column='id', unique=True)
    slug = TextField(unique=True)
    settings = JSONBField(default={})
    is_personal = BooleanField(default=False)
    workspace_id = ForeignKey(to_model=Workspaces, to_column='id', )
    _inverse_foreign_keys: ClassVar[dict[str, dict[str, str]]] = {'context_variables': {'from_model': 'ContextVariables', 'from_field': 'project_id', 'referenced_field': 'id', 'related_name': 'context_variables'}, 'tasks': {'from_model': 'Tasks', 'from_field': 'project_id', 'referenced_field': 'id', 'related_name': 'tasks'}, 'user_active_context': {'from_model': 'UserActiveContext', 'from_field': 'project_id', 'referenced_field': 'id', 'related_name': 'user_active_context'}, 'broker_values': {'from_model': 'BrokerValues', 'from_field': 'project_id', 'referenced_field': 'id', 'related_name': 'broker_values'}, 'user_files': {'from_model': 'UserFiles', 'from_field': 'project_id', 'referenced_field': 'id', 'related_name': 'user_files'}, 'cx_conversation': {'from_model': 'CxConversation', 'from_field': 'project_id', 'referenced_field': 'id', 'related_name': 'cx_conversation'}, 'project_members': {'from_model': 'ProjectMembers', 'from_field': 'project_id', 'referenced_field': 'id', 'related_name': 'project_members'}, 'project_invitations': {'from_model': 'ProjectInvitations', 'from_field': 'project_id', 'referenced_field': 'id', 'related_name': 'project_invitations'}, 'sandbox_instances': {'from_model': 'SandboxInstances', 'from_field': 'project_id', 'referenced_field': 'id', 'related_name': 'sandbox_instances'}, 'context_items': {'from_model': 'ContextItems', 'from_field': 'project_id', 'referenced_field': 'id', 'related_name': 'context_items'}, 'app_instances': {'from_model': 'AppInstances', 'from_field': 'project_id', 'referenced_field': 'id', 'related_name': 'app_instances'}, 'notes': {'from_model': 'Notes', 'from_field': 'project_id', 'referenced_field': 'id', 'related_name': 'notes'}, 'rs_topic': {'from_model': 'RsTopic', 'from_field': 'project_id', 'referenced_field': 'id', 'related_name': 'rs_topic'}, 'user_tables': {'from_model': 'UserTables', 'from_field': 'project_id', 'referenced_field': 'id', 'related_name': 'user_tables'}, 'transcripts': {'from_model': 'Transcripts', 'from_field': 'project_id', 'referenced_field': 'id', 'related_name': 'transcripts'}, 'workflow': {'from_model': 'Workflow', 'from_field': 'project_id', 'referenced_field': 'id', 'related_name': 'workflow'}, 'canvas_items': {'from_model': 'CanvasItems', 'from_field': 'project_id', 'referenced_field': 'id', 'related_name': 'canvas_items'}, 'prompts': {'from_model': 'Prompts', 'from_field': 'project_id', 'referenced_field': 'id', 'related_name': 'prompts'}}
    _database = "supabase_automation_matrix"



class TaskPriority(str, Enum):
    HIGH = "high"
    LOW = "low"
    MEDIUM = "medium"

class Tasks(Model):
    id = UUIDField(primary_key=True, null=False)
    title = TextField(null=False)
    description = TextField()
    project_id = ForeignKey(to_model=Projects, to_column='id', )
    status = TextField(null=False, default='incomplete')
    due_date = DateField()
    created_at = DateTimeField()
    updated_at = DateTimeField()
    user_id = ForeignKey(to_model=Users, to_column='id', to_schema='auth', )
    authenticated_read = BooleanField(default=False)
    parent_task_id = ForeignKey(to_model='Tasks', to_column='id', )
    priority = EnumField(enum_class=TaskPriority, )
    assignee_id = ForeignKey(to_model=Users, to_column='id', to_schema='auth', )
    settings = JSONBField(null=False, default={})
    _inverse_foreign_keys: ClassVar[dict[str, dict[str, str]]] = {'task_assignments': {'from_model': 'TaskAssignments', 'from_field': 'task_id', 'referenced_field': 'id', 'related_name': 'task_assignments'}, 'task_attachments': {'from_model': 'TaskAttachments', 'from_field': 'task_id', 'referenced_field': 'id', 'related_name': 'task_attachments'}, 'context_variables': {'from_model': 'ContextVariables', 'from_field': 'task_id', 'referenced_field': 'id', 'related_name': 'context_variables'}, 'task_comments': {'from_model': 'TaskComments', 'from_field': 'task_id', 'referenced_field': 'id', 'related_name': 'task_comments'}, 'user_active_context': {'from_model': 'UserActiveContext', 'from_field': 'task_id', 'referenced_field': 'id', 'related_name': 'user_active_context'}, 'broker_values': {'from_model': 'BrokerValues', 'from_field': 'task_id', 'referenced_field': 'id', 'related_name': 'broker_values'}, 'user_files': {'from_model': 'UserFiles', 'from_field': 'task_id', 'referenced_field': 'id', 'related_name': 'user_files'}, 'cx_conversation': {'from_model': 'CxConversation', 'from_field': 'task_id', 'referenced_field': 'id', 'related_name': 'cx_conversation'}, 'sandbox_instances': {'from_model': 'SandboxInstances', 'from_field': 'task_id', 'referenced_field': 'id', 'related_name': 'sandbox_instances'}, 'context_items': {'from_model': 'ContextItems', 'from_field': 'task_id', 'referenced_field': 'id', 'related_name': 'context_items'}, 'app_instances': {'from_model': 'AppInstances', 'from_field': 'task_id', 'referenced_field': 'id', 'related_name': 'app_instances'}, 'notes': {'from_model': 'Notes', 'from_field': 'task_id', 'referenced_field': 'id', 'related_name': 'notes'}, 'user_tables': {'from_model': 'UserTables', 'from_field': 'task_id', 'referenced_field': 'id', 'related_name': 'user_tables'}, 'transcripts': {'from_model': 'Transcripts', 'from_field': 'task_id', 'referenced_field': 'id', 'related_name': 'transcripts'}, 'workflow': {'from_model': 'Workflow', 'from_field': 'task_id', 'referenced_field': 'id', 'related_name': 'workflow'}, 'prompts': {'from_model': 'Prompts', 'from_field': 'task_id', 'referenced_field': 'id', 'related_name': 'prompts'}}
    _database = "supabase_automation_matrix"

class CxConversation(Model):
    id = UUIDField(primary_key=True, null=False)
    user_id = ForeignKey(to_model=Users, to_column='id', to_schema='auth', null=False)
    title = TextField()
    system_instruction = TextField()
    config = JSONBField(null=False, default={})
    status = TextField(null=False, default='active')
    message_count = SmallIntegerField(null=False, default=0)
    forked_from_id = ForeignKey(to_model='CxConversation', to_column='id', )
    forked_at_position = SmallIntegerField()
    created_at = DateTimeField(null=False)
    updated_at = DateTimeField(null=False)
    deleted_at = DateTimeField()
    metadata = JSONBField(null=False, default={})
    last_model_id = ForeignKey(to_model=AiModel, to_column='id', )
    parent_conversation_id = ForeignKey(to_model='CxConversation', to_column='id', )
    variables = JSONBField(null=False, default={})
    overrides = JSONBField(null=False, default={})
    description = TextField()
    keywords = TextArrayField()
    organization_id = ForeignKey(to_model=Organizations, to_column='id', )
    workspace_id = ForeignKey(to_model=Workspaces, to_column='id', )
    project_id = ForeignKey(to_model=Projects, to_column='id', )
    task_id = ForeignKey(to_model=Tasks, to_column='id', )
    _inverse_foreign_keys: ClassVar[dict[str, dict[str, str]]] = {'cx_tool_call': {'from_model': 'CxToolCall', 'from_field': 'conversation_id', 'referenced_field': 'id', 'related_name': 'cx_tool_call'}, 'cx_message': {'from_model': 'CxMessage', 'from_field': 'conversation_id', 'referenced_field': 'id', 'related_name': 'cx_message'}, 'cx_media': {'from_model': 'CxMedia', 'from_field': 'conversation_id', 'referenced_field': 'id', 'related_name': 'cx_media'}, 'cx_user_request': {'from_model': 'CxUserRequest', 'from_field': 'conversation_id', 'referenced_field': 'id', 'related_name': 'cx_user_request'}, 'cx_request': {'from_model': 'CxRequest', 'from_field': 'conversation_id', 'referenced_field': 'id', 'related_name': 'cx_request'}, 'canvas_items': {'from_model': 'CanvasItems', 'from_field': 'conversation_id', 'referenced_field': 'id', 'related_name': 'canvas_items'}}
    _database = "supabase_automation_matrix"

class Prompts(Model):
    id = UUIDField(primary_key=True, null=False)
    created_at = DateTimeField(null=False)
    updated_at = DateTimeField(null=False)
    name = CharField()
    messages = JSONBField()
    variable_defaults = JSONBField()
    tools = JSONBField()
    user_id = ForeignKey(to_model=Users, to_column='id', to_schema='auth', )
    settings = JSONBField()
    description = TextField()
    tags = TextArrayField(default=[])
    category = TextField()
    is_archived = BooleanField(null=False, default=False)
    is_favorite = BooleanField(null=False, default=False)
    model_id = ForeignKey(to_model=AiModel, to_column='id', )
    output_format = TextField()
    output_schema = JSONBField()
    dynamic_model = BooleanField(default=False)
    context_slots = JSONBField(null=False, default=[])
    organization_id = ForeignKey(to_model=Organizations, to_column='id', )
    workspace_id = ForeignKey(to_model=Workspaces, to_column='id', )
    project_id = ForeignKey(to_model=Projects, to_column='id', )
    task_id = ForeignKey(to_model=Tasks, to_column='id', )
    version = IntegerField(null=False, default=1)
    _inverse_foreign_keys: ClassVar[dict[str, dict[str, str]]] = {'system_prompts_new': {'from_model': 'SystemPromptsNew', 'from_field': 'source_prompt_id', 'referenced_field': 'id', 'related_name': 'system_prompts_new'}, 'prompt_actions': {'from_model': 'PromptActions', 'from_field': 'prompt_id', 'referenced_field': 'id', 'related_name': 'prompt_actions'}, 'system_prompts': {'from_model': 'SystemPrompts', 'from_field': 'source_prompt_id', 'referenced_field': 'id', 'related_name': 'system_prompts'}, 'prompt_versions': {'from_model': 'PromptVersions', 'from_field': 'prompt_id', 'referenced_field': 'id', 'related_name': 'prompt_versions'}, 'prompt_builtins': {'from_model': 'PromptBuiltins', 'from_field': 'source_prompt_id', 'referenced_field': 'id', 'related_name': 'prompt_builtins'}, 'prompt_apps': {'from_model': 'PromptApps', 'from_field': 'prompt_id', 'referenced_field': 'id', 'related_name': 'prompt_apps'}}
    _database = "supabase_automation_matrix"

class UserTables(Model):
    id = UUIDField(primary_key=True, null=False)
    table_name = CharField(null=False, max_length=255, unique=True)  # type: ignore[override]
    description = TextField()
    version = IntegerField(null=False, default=1)
    user_id = ForeignKey(to_model=Users, to_column='id', to_schema='auth', null=False, unique=True)
    is_public = BooleanField(null=False, default=False)
    authenticated_read = BooleanField(null=False, default=False)
    created_at = DateTimeField(null=False)
    updated_at = DateTimeField(null=False)
    row_ordering_config = JSONBField()
    organization_id = ForeignKey(to_model=Organizations, to_column='id', )
    workspace_id = ForeignKey(to_model=Workspaces, to_column='id', )
    project_id = ForeignKey(to_model=Projects, to_column='id', )
    task_id = ForeignKey(to_model=Tasks, to_column='id', )
    _inverse_foreign_keys: ClassVar[dict[str, dict[str, str]]] = {'table_data': {'from_model': 'TableData', 'from_field': 'table_id', 'referenced_field': 'id', 'related_name': 'table_data'}, 'table_fields': {'from_model': 'TableFields', 'from_field': 'table_id', 'referenced_field': 'id', 'related_name': 'table_fields'}}
    _database = "supabase_automation_matrix"

class CxMedia(Model):
    id = UUIDField(primary_key=True, null=False)
    conversation_id = ForeignKey(to_model=CxConversation, to_column='id', )
    user_id = ForeignKey(to_model=Users, to_column='id', to_schema='auth', null=False)
    kind = TextField(null=False)
    url = TextField(null=False)
    file_uri = TextField()
    mime_type = TextField()
    file_size_bytes = BigIntegerField()
    created_at = DateTimeField(null=False)
    deleted_at = DateTimeField()
    metadata = JSONBField(null=False, default={})
    _inverse_foreign_keys: ClassVar[dict[str, dict[str, str]]] = {}
    _database = "supabase_automation_matrix"

class CxMessage(Model):
    id = UUIDField(primary_key=True, null=False)
    conversation_id = ForeignKey(to_model=CxConversation, to_column='id', null=False)
    role = TextField(null=False)
    position = SmallIntegerField(null=False)
    status = TextField(null=False, default='active')
    content = JSONBField(null=False, default=[])
    created_at = DateTimeField(null=False)
    deleted_at = DateTimeField()
    metadata = JSONBField(null=False, default={})
    content_history = JSONBField()
    _inverse_foreign_keys: ClassVar[dict[str, dict[str, str]]] = {'cx_tool_call': {'from_model': 'CxToolCall', 'from_field': 'message_id', 'referenced_field': 'id', 'related_name': 'cx_tool_call'}}
    _database = "supabase_automation_matrix"

class CxUserRequest(Model):
    id = UUIDField(primary_key=True, null=False)
    conversation_id = ForeignKey(to_model=CxConversation, to_column='id', null=False)
    user_id = ForeignKey(to_model=Users, to_column='id', to_schema='auth', null=False)
    trigger_message_position = SmallIntegerField()
    total_input_tokens = IntegerField(null=False, default=0)
    total_output_tokens = IntegerField(null=False, default=0)
    total_cached_tokens = IntegerField(null=False, default=0)
    total_tokens = IntegerField(null=False, default=0)
    total_cost = DecimalField(default=0)
    total_duration_ms = IntegerField()
    api_duration_ms = IntegerField()
    tool_duration_ms = IntegerField()
    iterations = SmallIntegerField(null=False, default=1)
    total_tool_calls = SmallIntegerField(null=False, default=0)
    status = TextField(null=False, default='pending')
    finish_reason = TextField()
    error = TextField()
    result_start_position = SmallIntegerField()
    result_end_position = SmallIntegerField()
    created_at = DateTimeField(null=False)
    completed_at = DateTimeField()
    deleted_at = DateTimeField()
    metadata = JSONBField(null=False, default={})
    _inverse_foreign_keys: ClassVar[dict[str, dict[str, str]]] = {'cx_tool_call': {'from_model': 'CxToolCall', 'from_field': 'user_request_id', 'referenced_field': 'id', 'related_name': 'cx_tool_call'}, 'cx_request': {'from_model': 'CxRequest', 'from_field': 'user_request_id', 'referenced_field': 'id', 'related_name': 'cx_request'}}
    _database = "supabase_automation_matrix"

class PromptBuiltins(Model):
    id = UUIDField(primary_key=True, null=False)
    created_at = DateTimeField(null=False)
    updated_at = DateTimeField(null=False)
    name = CharField(null=False)
    description = TextField()
    messages = JSONBField(null=False)
    variable_defaults = JSONBField()
    tools = JSONBField()
    settings = JSONBField()
    created_by_user_id = ForeignKey(to_model=Users, to_column='id', to_schema='auth', )
    is_active = BooleanField(null=False, default=True)
    source_prompt_id = ForeignKey(to_model=Prompts, to_column='id', )
    source_prompt_snapshot_at = DateTimeField()
    tags = TextArrayField(default=[])
    category = TextField()
    model_id = ForeignKey(to_model=AiModel, to_column='id', )
    output_format = TextField()
    output_schema = JSONBField()
    is_archived = BooleanField(null=False, default=False)
    is_favorite = BooleanField(null=False, default=False)
    dynamic_model = BooleanField(default=False)
    context_slots = JSONBField(null=False, default=[])
    version = IntegerField(null=False, default=1)
    _inverse_foreign_keys: ClassVar[dict[str, dict[str, str]]] = {'prompt_shortcuts': {'from_model': 'PromptShortcuts', 'from_field': 'prompt_builtin_id', 'referenced_field': 'id', 'related_name': 'prompt_shortcuts'}, 'prompt_actions': {'from_model': 'PromptActions', 'from_field': 'prompt_builtin_id', 'referenced_field': 'id', 'related_name': 'prompt_actions'}, 'prompt_builtin_versions': {'from_model': 'PromptBuiltinVersions', 'from_field': 'builtin_id', 'referenced_field': 'id', 'related_name': 'prompt_builtin_versions'}}
    _database = "supabase_automation_matrix"

class TableData(Model):
    id = UUIDField(primary_key=True, null=False, unique=True)
    table_id = ForeignKey(to_model=UserTables, to_column='id', null=False, unique=True)
    data = JSONBField(null=False)
    user_id = ForeignKey(to_model=Users, to_column='id', to_schema='auth', null=False)
    is_public = BooleanField(null=False, default=False)
    authenticated_read = BooleanField(null=False, default=False)
    created_at = DateTimeField(null=False)
    updated_at = DateTimeField(null=False)
    _inverse_foreign_keys: ClassVar[dict[str, dict[str, str]]] = {}
    _database = "supabase_automation_matrix"

class CxRequest(Model):
    id = UUIDField(primary_key=True, null=False)
    user_request_id = ForeignKey(to_model=CxUserRequest, to_column='id', null=False)
    conversation_id = ForeignKey(to_model=CxConversation, to_column='id', null=False)
    api_class = TextField()
    iteration = SmallIntegerField(null=False, default=1)
    input_tokens = IntegerField()
    output_tokens = IntegerField()
    cached_tokens = IntegerField()
    total_tokens = IntegerField()
    cost = DecimalField()
    api_duration_ms = IntegerField()
    tool_duration_ms = IntegerField()
    total_duration_ms = IntegerField()
    tool_calls_count = SmallIntegerField(default=0)
    tool_calls_details = JSONBField()
    finish_reason = TextField()
    response_id = TextField()
    created_at = DateTimeField(null=False)
    deleted_at = DateTimeField()
    metadata = JSONBField(null=False, default={})
    ai_model_id = ForeignKey(to_model=AiModel, to_column='id', null=False)
    _inverse_foreign_keys: ClassVar[dict[str, dict[str, str]]] = {}
    _database = "supabase_automation_matrix"

class CxToolCall(Model):
    id = UUIDField(primary_key=True, null=False)
    conversation_id = ForeignKey(to_model=CxConversation, to_column='id', null=False)
    message_id = ForeignKey(to_model=CxMessage, to_column='id', )
    user_id = ForeignKey(to_model=Users, to_column='id', to_schema='auth', null=False)
    user_request_id = ForeignKey(to_model=CxUserRequest, to_column='id', )
    tool_name = TextField(null=False)
    tool_type = TextField(null=False, default='local')
    call_id = TextField(null=False)
    status = TextField(null=False, default='pending')
    arguments = JSONBField(null=False, default={})
    success = BooleanField(null=False, default=True)
    output = TextField()
    output_type = TextField(default='text')
    is_error = BooleanField(default=False)
    error_type = TextField()
    error_message = TextField()
    duration_ms = IntegerField(null=False, default=0)
    started_at = DateTimeField(null=False)
    completed_at = DateTimeField(null=False)
    input_tokens = IntegerField(default=0)
    output_tokens = IntegerField(default=0)
    total_tokens = IntegerField(default=0)
    cost_usd = DecimalField(default=0)
    iteration = IntegerField(null=False, default=0)
    retry_count = IntegerField(default=0)
    parent_call_id = ForeignKey(to_model='CxToolCall', to_column='id', )
    execution_events = JSONBField(default=[])
    persist_key = TextField()
    file_path = TextField()
    metadata = JSONBField(null=False, default={})
    created_at = DateTimeField(null=False)
    deleted_at = DateTimeField()
    _inverse_foreign_keys: ClassVar[dict[str, dict[str, str]]] = {}
    _database = "supabase_automation_matrix"


model_registry.register_all(
[
        AiProvider,
        CxAgentMemory,
        Organizations,
        ShortcutCategories,
        Tools,
        AiModel,
        ContentBlocks,
        Workspaces,
        Projects,
        Tasks,
        CxConversation,
        Prompts,
        UserTables,
        CxMedia,
        CxMessage,
        CxUserRequest,
        PromptBuiltins,
        TableData,
        CxRequest,
        CxToolCall,
        Users
    ]
)



@dataclass
class AiProviderDTO(BaseDTO):
    id: str

    @classmethod
    async def from_model(cls, model: AiProvider):
        return cls(id=str(model.id))


class AiProviderManager(BaseManager):
    def __init__(self):
        super().__init__(AiProvider, AiProviderDTO)

    def _initialize_manager(self):
        super()._initialize_manager()

    async def _initialize_runtime_data(self, item: AiProvider) -> None:
        pass
    


@dataclass
class CxAgentMemoryDTO(BaseDTO):
    id: str

    @classmethod
    async def from_model(cls, model: CxAgentMemory):
        return cls(id=str(model.id))


class CxAgentMemoryManager(BaseManager):
    def __init__(self):
        super().__init__(CxAgentMemory, CxAgentMemoryDTO)

    def _initialize_manager(self):
        super()._initialize_manager()

    async def _initialize_runtime_data(self, item: CxAgentMemory) -> None:
        pass
    


@dataclass
class OrganizationsDTO(BaseDTO):
    id: str

    @classmethod
    async def from_model(cls, model: Organizations):
        return cls(id=str(model.id))


class OrganizationsManager(BaseManager):
    def __init__(self):
        super().__init__(Organizations, OrganizationsDTO)

    def _initialize_manager(self):
        super()._initialize_manager()

    async def _initialize_runtime_data(self, item: Organizations) -> None:
        pass
    


@dataclass
class ShortcutCategoriesDTO(BaseDTO):
    id: str

    @classmethod
    async def from_model(cls, model: ShortcutCategories):
        return cls(id=str(model.id))


class ShortcutCategoriesManager(BaseManager):
    def __init__(self):
        super().__init__(ShortcutCategories, ShortcutCategoriesDTO)

    def _initialize_manager(self):
        super()._initialize_manager()

    async def _initialize_runtime_data(self, item: ShortcutCategories) -> None:
        pass
    


@dataclass
class ToolsDTO(BaseDTO):
    id: str

    @classmethod
    async def from_model(cls, model: Tools):
        return cls(id=str(model.id))


class ToolsManager(BaseManager):
    def __init__(self):
        super().__init__(Tools, ToolsDTO)

    def _initialize_manager(self):
        super()._initialize_manager()

    async def _initialize_runtime_data(self, item: Tools) -> None:
        pass
    


@dataclass
class AiModelDTO(BaseDTO):
    id: str

    @classmethod
    async def from_model(cls, model: AiModel):
        return cls(id=str(model.id))


class AiModelManager(BaseManager):
    def __init__(self):
        super().__init__(AiModel, AiModelDTO)

    def _initialize_manager(self):
        super()._initialize_manager()

    async def _initialize_runtime_data(self, item: AiModel) -> None:
        pass
    


@dataclass
class ContentBlocksDTO(BaseDTO):
    id: str

    @classmethod
    async def from_model(cls, model: ContentBlocks):
        return cls(id=str(model.id))


class ContentBlocksManager(BaseManager):
    def __init__(self):
        super().__init__(ContentBlocks, ContentBlocksDTO)

    def _initialize_manager(self):
        super()._initialize_manager()

    async def _initialize_runtime_data(self, item: ContentBlocks) -> None:
        pass
    


@dataclass
class WorkspacesDTO(BaseDTO):
    id: str

    @classmethod
    async def from_model(cls, model: Workspaces):
        return cls(id=str(model.id))


class WorkspacesManager(BaseManager):
    def __init__(self):
        super().__init__(Workspaces, WorkspacesDTO)

    def _initialize_manager(self):
        super()._initialize_manager()

    async def _initialize_runtime_data(self, item: Workspaces) -> None:
        pass
    


@dataclass
class ProjectsDTO(BaseDTO):
    id: str

    @classmethod
    async def from_model(cls, model: Projects):
        return cls(id=str(model.id))


class ProjectsManager(BaseManager):
    def __init__(self):
        super().__init__(Projects, ProjectsDTO)

    def _initialize_manager(self):
        super()._initialize_manager()

    async def _initialize_runtime_data(self, item: Projects) -> None:
        pass
    


@dataclass
class TasksDTO(BaseDTO):
    id: str

    @classmethod
    async def from_model(cls, model: Tasks):
        return cls(id=str(model.id))


class TasksManager(BaseManager):
    def __init__(self):
        super().__init__(Tasks, TasksDTO)

    def _initialize_manager(self):
        super()._initialize_manager()

    async def _initialize_runtime_data(self, item: Tasks) -> None:
        pass
    


@dataclass
class CxConversationDTO(BaseDTO):
    id: str

    @classmethod
    async def from_model(cls, model: CxConversation):
        return cls(id=str(model.id))


class CxConversationManager(BaseManager):
    def __init__(self):
        super().__init__(CxConversation, CxConversationDTO)

    def _initialize_manager(self):
        super()._initialize_manager()

    async def _initialize_runtime_data(self, item: CxConversation) -> None:
        pass
    


@dataclass
class PromptsDTO(BaseDTO):
    id: str

    @classmethod
    async def from_model(cls, model: Prompts):
        return cls(id=str(model.id))


class PromptsManager(BaseManager):
    def __init__(self):
        super().__init__(Prompts, PromptsDTO)

    def _initialize_manager(self):
        super()._initialize_manager()

    async def _initialize_runtime_data(self, item: Prompts) -> None:
        pass
    


@dataclass
class UserTablesDTO(BaseDTO):
    id: str

    @classmethod
    async def from_model(cls, model: UserTables):
        return cls(id=str(model.id))


class UserTablesManager(BaseManager):
    def __init__(self):
        super().__init__(UserTables, UserTablesDTO)

    def _initialize_manager(self):
        super()._initialize_manager()

    async def _initialize_runtime_data(self, item: UserTables) -> None:
        pass
    


@dataclass
class CxMediaDTO(BaseDTO):
    id: str

    @classmethod
    async def from_model(cls, model: CxMedia):
        return cls(id=str(model.id))


class CxMediaManager(BaseManager):
    def __init__(self):
        super().__init__(CxMedia, CxMediaDTO)

    def _initialize_manager(self):
        super()._initialize_manager()

    async def _initialize_runtime_data(self, item: CxMedia) -> None:
        pass
    


@dataclass
class CxMessageDTO(BaseDTO):
    id: str

    @classmethod
    async def from_model(cls, model: CxMessage):
        return cls(id=str(model.id))


class CxMessageManager(BaseManager):
    def __init__(self):
        super().__init__(CxMessage, CxMessageDTO)

    def _initialize_manager(self):
        super()._initialize_manager()

    async def _initialize_runtime_data(self, item: CxMessage) -> None:
        pass
    


@dataclass
class CxUserRequestDTO(BaseDTO):
    id: str

    @classmethod
    async def from_model(cls, model: CxUserRequest):
        return cls(id=str(model.id))


class CxUserRequestManager(BaseManager):
    def __init__(self):
        super().__init__(CxUserRequest, CxUserRequestDTO)

    def _initialize_manager(self):
        super()._initialize_manager()

    async def _initialize_runtime_data(self, item: CxUserRequest) -> None:
        pass
    


@dataclass
class PromptBuiltinsDTO(BaseDTO):
    id: str

    @classmethod
    async def from_model(cls, model: PromptBuiltins):
        return cls(id=str(model.id))


class PromptBuiltinsManager(BaseManager):
    def __init__(self):
        super().__init__(PromptBuiltins, PromptBuiltinsDTO)

    def _initialize_manager(self):
        super()._initialize_manager()

    async def _initialize_runtime_data(self, item: PromptBuiltins) -> None:
        pass
    


@dataclass
class TableDataDTO(BaseDTO):
    id: str

    @classmethod
    async def from_model(cls, model: TableData):
        return cls(id=str(model.id))


class TableDataManager(BaseManager):
    def __init__(self):
        super().__init__(TableData, TableDataDTO)

    def _initialize_manager(self):
        super()._initialize_manager()

    async def _initialize_runtime_data(self, item: TableData) -> None:
        pass
    


@dataclass
class CxRequestDTO(BaseDTO):
    id: str

    @classmethod
    async def from_model(cls, model: CxRequest):
        return cls(id=str(model.id))


class CxRequestManager(BaseManager):
    def __init__(self):
        super().__init__(CxRequest, CxRequestDTO)

    def _initialize_manager(self):
        super()._initialize_manager()

    async def _initialize_runtime_data(self, item: CxRequest) -> None:
        pass
    


@dataclass
class CxToolCallDTO(BaseDTO):
    id: str

    @classmethod
    async def from_model(cls, model: CxToolCall):
        return cls(id=str(model.id))


class CxToolCallManager(BaseManager):
    def __init__(self):
        super().__init__(CxToolCall, CxToolCallDTO)

    def _initialize_manager(self):
        super()._initialize_manager()

    async def _initialize_runtime_data(self, item: CxToolCall) -> None:
        pass