-- 移除无法自动结束的提交未知状态，并将遗留任务恢复到可重试队列。
UPDATE drama_parse_tasks
SET status = 'retry_wait',
    error_code = NULL,
    error_message = '连接超时，正在自动重试',
    lease_owner = NULL,
    lease_until = NULL
WHERE status = 'submit_unknown';

UPDATE generation_tasks
SET status = 'pending_submission',
    next_submit_at = CURRENT_TIMESTAMP,
    slot_released_at = CURRENT_TIMESTAMP,
    error_code = NULL,
    error_message = '连接超时，正在自动重试',
    lease_owner = NULL,
    lease_until = NULL
WHERE status = 'submit_unknown';

ALTER TABLE drama_parse_tasks DROP CONSTRAINT drama_parse_tasks_status_check;
ALTER TABLE drama_parse_tasks
    ADD CONSTRAINT drama_parse_tasks_status_check
    CHECK (status IN ('queued', 'running', 'retry_wait', 'succeeded', 'failed', 'cancel_requested', 'cancelled'));

ALTER TABLE generation_tasks DROP CONSTRAINT generation_tasks_status_check;
ALTER TABLE generation_tasks
    ADD CONSTRAINT generation_tasks_status_check
    CHECK (status IN ('pending_submission', 'submitting', 'submitted', 'processing', 'result_ready', 'downloading', 'succeeded', 'failed', 'cancel_requested', 'cancelled'));

DROP INDEX idx_drama_parse_tasks_recovery;
CREATE INDEX idx_drama_parse_tasks_recovery
    ON drama_parse_tasks(status, lease_until)
    WHERE status IN ('queued', 'running', 'retry_wait');

DROP INDEX uq_drama_episode_active_parse;
CREATE UNIQUE INDEX uq_drama_episode_active_parse
    ON drama_parse_tasks(episode_id)
    WHERE status IN ('queued', 'running', 'retry_wait', 'cancel_requested');

DROP INDEX uq_script_analysis_active_task;
CREATE UNIQUE INDEX uq_script_analysis_active_task
    ON generation_tasks(script_analysis_id)
    WHERE script_analysis_id IS NOT NULL
      AND status IN ('pending_submission', 'submitting', 'submitted', 'processing', 'result_ready', 'downloading', 'cancel_requested');
