"""Add pgvector extension and tree_embeddings table.

Revision ID: 042
Revises: 041
Create Date: 2026-03-04
"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

# revision identifiers
revision: str = "042"
down_revision: str = "041"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    op.execute("CREATE EXTENSION IF NOT EXISTS vector")

    op.create_table(
        "tree_embeddings",
        sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True, server_default=sa.text("gen_random_uuid()")),
        sa.Column("tree_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("trees.id", ondelete="CASCADE"), nullable=False),
        sa.Column("account_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("accounts.id", ondelete="CASCADE"), nullable=True),
        sa.Column("chunk_type", sa.String(30), nullable=False),
        sa.Column("node_type", sa.String(30), nullable=True),
        sa.Column("node_id", sa.String(100), nullable=True),
        sa.Column("chunk_text", sa.Text(), nullable=False),
        sa.Column("embedding_model", sa.String(50), nullable=False, server_default="voyage-3.5"),
        sa.Column("meta", postgresql.JSONB(), nullable=False, server_default=sa.text("'{}'::jsonb")),
        sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("now()")),
        sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("now()")),
    )

    op.execute("ALTER TABLE tree_embeddings ADD COLUMN embedding vector(1024)")

    op.create_index("ix_tree_embeddings_account_id", "tree_embeddings", ["account_id"])
    op.create_index("ix_tree_embeddings_tree_id", "tree_embeddings", ["tree_id"])


def downgrade() -> None:
    op.drop_table("tree_embeddings")
    op.execute("DROP EXTENSION IF EXISTS vector")