ALTER TABLE kol_prompts
    ADD COLUMN IF NOT EXISTS prompt_asset_key TEXT,
    ADD COLUMN IF NOT EXISTS schema_json JSONB NOT NULL DEFAULT '{}'::jsonb,
    ADD COLUMN IF NOT EXISTS card_config_json JSONB NOT NULL DEFAULT '{}'::jsonb;

WITH preferred_revisions AS (
    SELECT DISTINCT ON (p.id)
           p.id AS prompt_id,
           pr.prompt_asset_key,
           pr.schema_json,
           pr.card_config_json
    FROM kol_prompts p
    JOIN kol_prompt_revisions pr ON pr.prompt_id = p.id
    ORDER BY p.id,
             CASE
                 WHEN p.published_revision_no IS NOT NULL AND pr.revision_no = p.published_revision_no THEN 0
                 WHEN p.draft_revision_no IS NOT NULL AND pr.revision_no = p.draft_revision_no THEN 1
                 ELSE 2
             END,
             pr.revision_no DESC
)
UPDATE kol_prompts p
SET prompt_asset_key = r.prompt_asset_key,
    schema_json = COALESCE(r.schema_json, '{}'::jsonb),
    card_config_json = COALESCE(r.card_config_json, '{}'::jsonb)
FROM preferred_revisions r
WHERE p.id = r.prompt_id
  AND (p.prompt_asset_key IS NULL OR btrim(p.prompt_asset_key) = '');

UPDATE kol_prompts
SET published_revision_no = 1,
    draft_revision_no = NULL
WHERE prompt_asset_key IS NOT NULL
  AND btrim(prompt_asset_key) <> '';

ALTER TABLE kol_usage_logs
    DROP CONSTRAINT IF EXISTS fk_kol_usage_logs_prompt_revision;
