-- Story 1087: split the legacy `stage` column on `pipeline_items` into a
-- `(pipeline, status)` pair so the read side no longer needs to re-derive the
-- display column and badge from the stage string.
--
-- The migration is additive: `stage` is retained for backwards compatibility
-- while remaining Step E callers are migrated.  The backup of `pipeline.db`
-- written by `shadow_write::init` immediately before this migration runs is
-- the recovery path if the backfill produces an unexpected projection.

ALTER TABLE pipeline_items ADD COLUMN pipeline TEXT NOT NULL DEFAULT '';
ALTER TABLE pipeline_items ADD COLUMN status   TEXT NOT NULL DEFAULT '';

-- Backfill `pipeline` from the existing `stage` column.  Every wire-form
-- stage string emitted by `stage_dir_name` maps to exactly one of the seven
-- Pipeline columns defined in `pipeline_state::types::Pipeline::as_str`.
-- Legacy directory strings (`1_backlog`, `2_current`, ...) are also handled
-- so that databases predating story 934 migrate cleanly.
UPDATE pipeline_items SET pipeline = CASE stage
    WHEN 'upcoming'            THEN 'backlog'
    WHEN 'backlog'             THEN 'backlog'
    WHEN '1_backlog'           THEN 'backlog'
    WHEN 'coding'              THEN 'coding'
    WHEN 'blocked'             THEN 'coding'
    WHEN '2_current'           THEN 'coding'
    WHEN 'qa'                  THEN 'qa'
    WHEN 'review_hold'         THEN 'qa'
    WHEN '3_qa'                THEN 'qa'
    WHEN 'merge'               THEN 'merge'
    WHEN 'merge_failure'       THEN 'merge'
    WHEN 'merge_failure_final' THEN 'merge'
    WHEN '4_merge'             THEN 'merge'
    WHEN 'done'                THEN 'done'
    WHEN '5_done'              THEN 'done'
    WHEN 'abandoned'           THEN 'closed'
    WHEN 'superseded'          THEN 'closed'
    WHEN 'rejected'            THEN 'closed'
    WHEN 'archived'            THEN 'archived'
    WHEN '6_archived'          THEN 'archived'
    WHEN 'frozen'              THEN 'coding'
    ELSE ''
END;

-- Backfill `status` (badge) from the existing `stage` column.
UPDATE pipeline_items SET status = CASE stage
    WHEN 'frozen'              THEN 'frozen'
    WHEN 'review_hold'         THEN 'review-hold'
    WHEN 'blocked'             THEN 'blocked'
    WHEN 'merge_failure'       THEN 'merge-failure'
    WHEN 'merge_failure_final' THEN 'merge-failure-final'
    WHEN 'abandoned'           THEN 'abandoned'
    WHEN 'superseded'          THEN 'superseded'
    WHEN 'rejected'            THEN 'rejected'
    WHEN 'done'                THEN 'done'
    WHEN '5_done'              THEN 'done'
    ELSE 'active'
END;
