-- Migration Script: Move existing chunks to pre_chunks table
-- Purpose: Test new Rule 1 architecture (pre_chunks → Rule 1 → chunks)
-- Date: 2026-04-27

-- Target video: Charade 1963

BEGIN;

-- 1. Clear existing pre_chunks for this video
DELETE FROM dev.pre_chunks WHERE file_uuid::text LIKE '384b0ff4%';

-- 2. Migrate sentence chunks (ASR data) to pre_chunks
INSERT INTO dev.pre_chunks (
    file_uuid, processor_type, coordinate_type, coordinate_index,
    timestamp, start_frame, end_frame, start_time, end_time, fps, data
)
SELECT 
    uuid, 'asr', 'time', chunk_index,
    (start_frame + end_frame) / 2.0 / fps,
    start_frame, end_frame, start_frame / fps, end_frame / fps, fps,
    jsonb_build_object(
        'text', content->'data'->>'text',
        'text_normalized', lower(content->'data'->>'text'),
        'language', 'en', 'language_probability', 1.0
    )
FROM dev.chunks
WHERE uuid::text LIKE '384b0ff4%' AND chunk_type = 'sentence';

-- 3. Migrate cut chunks (scene data) to pre_chunks
INSERT INTO dev.pre_chunks (
    file_uuid, processor_type, coordinate_type, coordinate_index,
    timestamp, start_frame, end_frame, start_time, end_time, fps, data
)
SELECT 
    uuid, 'cut', 'time', CAST(content->'data'->>'scene_number' AS INTEGER),
    (start_frame + end_frame) / 2.0 / fps,
    start_frame, end_frame, start_frame / fps, end_frame / fps, fps,
    jsonb_build_object('scene_number', content->'data'->>'scene_number')
FROM dev.chunks
WHERE uuid::text LIKE '384b0ff4%' AND chunk_type = 'cut';

COMMIT;

-- 4. Verify migration
SELECT 
    processor_type,
    coordinate_type,
    COUNT(*) as count,
    MIN(start_frame) as min_frame,
    MAX(end_frame) as max_frame
FROM dev.pre_chunks
WHERE file_uuid = '384b0ff44aaaa1f1'
GROUP BY processor_type, coordinate_type;

COMMIT;

-- Post-migration stats
SELECT 'Migration completed' as status;
SELECT 
    'ASR pre_chunks: ' || COUNT(*) as asr_count
FROM dev.pre_chunks 
WHERE file_uuid = '384b0ff44aaaa1f1' AND processor_type = 'asr';

SELECT 
    'CUT pre_chunks: ' || COUNT(*) as cut_count
FROM dev.pre_chunks 
WHERE file_uuid = '384b0ff44aaaa1f1' AND processor_type = 'cut';