"""Add file_name to FileAgent association table and FileContent table

Revision ID: cdd4a1c11aee
Revises: 614c4e53b66e
Create Date: 2025-06-03 15:35:59.623704

"""

from typing import Sequence, Union

import sqlalchemy as sa

from alembic import op
from letta.settings import settings

# revision identifiers, used by Alembic.
revision: str = "cdd4a1c11aee"
down_revision: Union[str, None] = "614c4e53b66e"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # Skip this migration for SQLite
    if not settings.letta_pg_uri_no_default:
        return

    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table(
        "file_contents",
        sa.Column("file_id", sa.String(), nullable=False),
        sa.Column("text", sa.Text(), nullable=False),
        sa.Column("id", sa.String(), nullable=False),
        sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=True),
        sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=True),
        sa.Column("is_deleted", sa.Boolean(), server_default=sa.text("FALSE"), nullable=False),
        sa.Column("_created_by_id", sa.String(), nullable=True),
        sa.Column("_last_updated_by_id", sa.String(), nullable=True),
        sa.ForeignKeyConstraint(["file_id"], ["files.id"], ondelete="CASCADE"),
        sa.PrimaryKeyConstraint("file_id", "id"),
    )
    # add the column, nullable for now
    op.add_column("files_agents", sa.Column("file_name", sa.String(), nullable=True))

    # back-fill using a single UPDATE … FROM join
    op.execute(
        """
            UPDATE files_agents fa
            SET    file_name = f.file_name
            FROM   files f
            WHERE  fa.file_id = f.id;
        """
    )

    # now make it NOT NULL
    op.alter_column("files_agents", "file_name", nullable=False)
    op.create_index("ix_files_agents_agent_file_name", "files_agents", ["agent_id", "file_name"], unique=False)
    op.create_unique_constraint("uq_files_agents_agent_file_name", "files_agents", ["agent_id", "file_name"])
    # ### end Alembic commands ###


def downgrade() -> None:
    # Skip this migration for SQLite
    if not settings.letta_pg_uri_no_default:
        return

    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint("uq_files_agents_agent_file_name", "files_agents", type_="unique")
    op.drop_index("ix_files_agents_agent_file_name", table_name="files_agents")
    op.drop_column("files_agents", "file_name")
    op.drop_table("file_contents")
    # ### end Alembic commands ###
