"""normalize workstream lifecycle states

Revision ID: u8p9q0r1s2t3
Revises: t7o8p9q0r1s2
Create Date: 2026-05-17

"""
from alembic import op

revision = "u8p9q0r1s2t3"
down_revision = "t7o8p9q0r1s2"
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.execute(
        """
        UPDATE workstreams
        SET status = 'finished'
        WHERE status IN ('completed', 'accepted', 'done')
        """
    )
    op.execute(
        """
        UPDATE workstreams ws
        SET status = 'active'
        WHERE status = 'todo'
          AND EXISTS (
            SELECT 1
            FROM tasks t
            WHERE t.workstream_id = ws.id
              AND t.status <> 'todo'
          )
        """
    )
    op.execute(
        """
        UPDATE workstreams
        SET status = 'ready'
        WHERE status = 'todo'
        """
    )


def downgrade() -> None:
    op.execute("UPDATE workstreams SET status = 'completed' WHERE status = 'finished'")
    op.execute("UPDATE workstreams SET status = 'active' WHERE status IN ('proposed', 'ready', 'backlog')")
