-- Migration: Monthly → Daily partition key
-- PARTITION BY (symbol, threshold_decimal_bps, toYYYYMM(...))
--          → (symbol, threshold_decimal_bps, toYYYYMMDD(...))
--
-- Prerequisites:
--   1. Stop sidecar:  sudo systemctl stop opendeviationbar-sidecar
--   2. Stop kintsugi: sudo systemctl stop opendeviationbar-kintsugi
--   3. Stop heartbeat: sudo systemctl stop opendeviationbar-heartbeat.timer
--
-- Run: clickhouse-client --multiquery < migrate_partition_yyyymm_to_yyyymmdd.sql
-- Estimated time: ~5 min for 19M bars

-- Step 1: Create new table with daily partitioning
CREATE TABLE opendeviationbar_cache.open_deviation_bars_daily AS opendeviationbar_cache.open_deviation_bars
ENGINE = ReplacingMergeTree(computed_at)
PARTITION BY (symbol, threshold_decimal_bps, toYYYYMMDD(toDateTime(close_time_us / 1000000, 'UTC')))
ORDER BY (symbol, threshold_decimal_bps, ouroboros_mode, first_agg_trade_id)
SETTINGS non_replicated_deduplication_window = 1000,
    deduplicate_merge_projection_mode = 'drop';

-- Step 2: Copy all data
INSERT INTO opendeviationbar_cache.open_deviation_bars_daily
SELECT * FROM opendeviationbar_cache.open_deviation_bars;

-- Step 3: Verify row counts match
SELECT
    (SELECT count() FROM opendeviationbar_cache.open_deviation_bars) AS old_count,
    (SELECT count() FROM opendeviationbar_cache.open_deviation_bars_daily) AS new_count,
    old_count = new_count AS counts_match;

-- Step 4: Re-add projection (lost during CREATE ... AS)
ALTER TABLE opendeviationbar_cache.open_deviation_bars_daily ADD PROJECTION IF NOT EXISTS prj_time_range
    (SELECT * ORDER BY (symbol, threshold_decimal_bps, close_time_us));

-- Step 5: Atomic rename (old → backup, new → production)
RENAME TABLE
    opendeviationbar_cache.open_deviation_bars TO opendeviationbar_cache.open_deviation_bars_monthly_backup,
    opendeviationbar_cache.open_deviation_bars_daily TO opendeviationbar_cache.open_deviation_bars;

-- Step 6: Verify partition key
SELECT partition_key
FROM system.tables
WHERE database = 'opendeviationbar_cache' AND name = 'open_deviation_bars';

-- After verification, drop backup:
-- DROP TABLE opendeviationbar_cache.open_deviation_bars_monthly_backup;
--
-- Then restart services:
--   sudo systemctl start opendeviationbar-sidecar
--   sudo systemctl start opendeviationbar-kintsugi
--   sudo systemctl start opendeviationbar-heartbeat.timer
