"""create new runs table and remove legacy tables

Revision ID: 567e9fe06270
Revises: 3d2e9fb40a3c
Create Date: 2025-09-22 15:22:28.651178

"""

from typing import Sequence, Union

import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

from alembic import op

# revision identifiers, used by Alembic.
revision: str = "567e9fe06270"
down_revision: Union[str, None] = "3d2e9fb40a3c"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table(
        "runs",
        sa.Column("id", sa.String(), nullable=False),
        sa.Column("status", sa.String(), nullable=False),
        sa.Column("completed_at", sa.DateTime(), nullable=True),
        sa.Column("stop_reason", sa.String(), nullable=True),
        sa.Column("background", sa.Boolean(), nullable=True),
        sa.Column("metadata_", sa.JSON(), nullable=True),
        sa.Column("request_config", sa.JSON(), nullable=True),
        sa.Column("agent_id", sa.String(), nullable=False),
        sa.Column("callback_url", sa.String(), nullable=True),
        sa.Column("callback_sent_at", sa.DateTime(), nullable=True),
        sa.Column("callback_status_code", sa.Integer(), nullable=True),
        sa.Column("callback_error", sa.String(), nullable=True),
        sa.Column("ttft_ns", sa.BigInteger(), nullable=True),
        sa.Column("total_duration_ns", sa.BigInteger(), nullable=True),
        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.Column("organization_id", sa.String(), nullable=False),
        sa.Column("project_id", sa.String(), nullable=True),
        sa.Column("base_template_id", sa.String(), nullable=True),
        sa.Column("template_id", sa.String(), nullable=True),
        sa.Column("deployment_id", sa.String(), nullable=True),
        sa.ForeignKeyConstraint(
            ["agent_id"],
            ["agents.id"],
        ),
        sa.ForeignKeyConstraint(
            ["organization_id"],
            ["organizations.id"],
        ),
        sa.PrimaryKeyConstraint("id"),
    )
    op.create_index("ix_runs_agent_id", "runs", ["agent_id"], unique=False)
    op.create_index("ix_runs_created_at", "runs", ["created_at", "id"], unique=False)
    op.create_index("ix_runs_organization_id", "runs", ["organization_id"], unique=False)
    op.drop_index(op.f("ix_agents_runs_agent_id_run_id"), table_name="agents_runs")
    op.drop_index(op.f("ix_agents_runs_run_id_agent_id"), table_name="agents_runs")
    op.drop_table("agents_runs")
    op.drop_table("job_messages")
    op.add_column("messages", sa.Column("run_id", sa.String(), nullable=True))
    op.create_foreign_key("fk_messages_run_id", "messages", "runs", ["run_id"], ["id"], ondelete="SET NULL")
    op.add_column("step_metrics", sa.Column("run_id", sa.String(), nullable=True))
    op.drop_constraint(op.f("step_metrics_job_id_fkey"), "step_metrics", type_="foreignkey")
    op.create_foreign_key("fk_step_metrics_run_id", "step_metrics", "runs", ["run_id"], ["id"], ondelete="SET NULL")
    op.drop_column("step_metrics", "job_id")
    op.add_column("steps", sa.Column("run_id", sa.String(), nullable=True))
    op.drop_index(op.f("ix_steps_job_id"), table_name="steps")
    op.create_index("ix_steps_run_id", "steps", ["run_id"], unique=False)
    op.drop_constraint(op.f("fk_steps_job_id"), "steps", type_="foreignkey")
    op.create_foreign_key("fk_steps_run_id", "steps", "runs", ["run_id"], ["id"], ondelete="SET NULL")
    op.drop_column("steps", "job_id")
    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column("steps", sa.Column("job_id", sa.VARCHAR(), autoincrement=False, nullable=True))
    op.drop_constraint("fk_steps_run_id", "steps", type_="foreignkey")
    op.create_foreign_key(op.f("fk_steps_job_id"), "steps", "jobs", ["job_id"], ["id"], ondelete="SET NULL")
    op.drop_index("ix_steps_run_id", table_name="steps")
    op.create_index(op.f("ix_steps_job_id"), "steps", ["job_id"], unique=False)
    op.drop_column("steps", "run_id")
    op.add_column("step_metrics", sa.Column("job_id", sa.VARCHAR(), autoincrement=False, nullable=True))
    op.drop_constraint("fk_step_metrics_run_id", "step_metrics", type_="foreignkey")
    op.create_foreign_key(op.f("step_metrics_job_id_fkey"), "step_metrics", "jobs", ["job_id"], ["id"], ondelete="SET NULL")
    op.drop_column("step_metrics", "run_id")
    op.drop_constraint("fk_messages_run_id", "messages", type_="foreignkey")
    op.drop_column("messages", "run_id")
    op.create_table(
        "job_messages",
        sa.Column("id", sa.INTEGER(), autoincrement=True, nullable=False),
        sa.Column("job_id", sa.VARCHAR(), autoincrement=False, nullable=False),
        sa.Column("message_id", sa.VARCHAR(), autoincrement=False, nullable=False),
        sa.Column("created_at", postgresql.TIMESTAMP(timezone=True), server_default=sa.text("now()"), autoincrement=False, nullable=True),
        sa.Column("updated_at", postgresql.TIMESTAMP(timezone=True), server_default=sa.text("now()"), autoincrement=False, nullable=True),
        sa.Column("is_deleted", sa.BOOLEAN(), server_default=sa.text("false"), autoincrement=False, nullable=False),
        sa.Column("_created_by_id", sa.VARCHAR(), autoincrement=False, nullable=True),
        sa.Column("_last_updated_by_id", sa.VARCHAR(), autoincrement=False, nullable=True),
        sa.ForeignKeyConstraint(["job_id"], ["jobs.id"], name=op.f("fk_job_messages_job_id"), ondelete="CASCADE"),
        sa.ForeignKeyConstraint(["message_id"], ["messages.id"], name=op.f("fk_job_messages_message_id"), ondelete="CASCADE"),
        sa.PrimaryKeyConstraint("id", name=op.f("pk_job_messages")),
        sa.UniqueConstraint(
            "job_id", "message_id", name=op.f("unique_job_message"), postgresql_include=[], postgresql_nulls_not_distinct=False
        ),
    )
    op.create_table(
        "agents_runs",
        sa.Column("agent_id", sa.VARCHAR(), autoincrement=False, nullable=False),
        sa.Column("run_id", sa.VARCHAR(), autoincrement=False, nullable=False),
        sa.ForeignKeyConstraint(["agent_id"], ["agents.id"], name=op.f("agents_runs_agent_id_fkey")),
        sa.ForeignKeyConstraint(["run_id"], ["jobs.id"], name=op.f("agents_runs_run_id_fkey")),
        sa.PrimaryKeyConstraint("agent_id", "run_id", name=op.f("unique_agent_run")),
    )
    op.create_index(op.f("ix_agents_runs_run_id_agent_id"), "agents_runs", ["run_id", "agent_id"], unique=False)
    op.create_index(op.f("ix_agents_runs_agent_id_run_id"), "agents_runs", ["agent_id", "run_id"], unique=False)
    op.drop_index("ix_runs_organization_id", table_name="runs")
    op.drop_index("ix_runs_created_at", table_name="runs")
    op.drop_index("ix_runs_agent_id", table_name="runs")
    op.drop_table("runs")
    # ### end Alembic commands ###
