"""Changed timestamping fields in process_steps.

Revision ID: 93fc5834c7e5
Revises: 4b58e336d1bf
Create Date: 2025-07-01 14:20:44.755694

"""

import sqlalchemy as sa
from alembic import op

from orchestrator import db

# revision identifiers, used by Alembic.
revision = "93fc5834c7e5"
down_revision = "4b58e336d1bf"
branch_labels = None
depends_on = None


def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column(
        "process_steps",
        sa.Column(
            "started_at",
            db.UtcTimestamp(timezone=True),
            server_default=sa.text("statement_timestamp()"),
            nullable=False,
        ),
    )
    op.alter_column("process_steps", "executed_at", new_column_name="completed_at")
    # conn = op.get_bind()
    # sa.select
    # ### end Alembic commands ###
    # Backfill started_at field correctly using proper aliasing
    op.execute(
        """
        WITH backfill_started_at AS (
            SELECT
                ps1.stepid,
                COALESCE(prev.completed_at, p.started_at) AS new_started_at
            FROM process_steps ps1
            JOIN processes p ON ps1.pid = p.pid
            LEFT JOIN LATERAL (
                SELECT ps2.completed_at
                FROM process_steps ps2
                WHERE ps2.pid = ps1.pid AND ps2.completed_at < ps1.completed_at
                ORDER BY ps2.completed_at DESC
                LIMIT 1
            ) prev ON true
        )
        UPDATE process_steps
        SET started_at = b.new_started_at
        FROM backfill_started_at b
        WHERE process_steps.stepid = b.stepid;
    """
    )


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column("process_steps", "started_at")
    op.alter_column("process_steps", "completed_at", new_column_name="executed_at")
    # ### end Alembic commands ###
