-- 创建模板片段权重配置表
-- 用于存储每个模板片段对不同AI分类的权重配置
-- 支持模板级别的权重自定义，而不是全局权重

CREATE TABLE IF NOT EXISTS template_segment_weights (
    id TEXT PRIMARY KEY,
    template_id TEXT NOT NULL,
    track_segment_id TEXT NOT NULL,
    ai_classification_id TEXT NOT NULL,
    weight INTEGER NOT NULL DEFAULT 0,
    created_at DATETIME NOT NULL DEFAULT (datetime('now', 'utc') || 'Z'),
    updated_at DATETIME NOT NULL DEFAULT (datetime('now', 'utc') || 'Z'),
    
    -- 外键约束
    FOREIGN KEY (template_id) REFERENCES templates (id) ON DELETE CASCADE,
    FOREIGN KEY (track_segment_id) REFERENCES track_segments (id) ON DELETE CASCADE,
    FOREIGN KEY (ai_classification_id) REFERENCES ai_classifications (id) ON DELETE CASCADE,
    
    -- 唯一约束：每个模板片段对每个AI分类只能有一个权重配置
    UNIQUE(template_id, track_segment_id, ai_classification_id)
);

-- 创建索引以提高查询性能
CREATE INDEX IF NOT EXISTS idx_template_segment_weights_template_id 
    ON template_segment_weights(template_id);

CREATE INDEX IF NOT EXISTS idx_template_segment_weights_track_segment_id 
    ON template_segment_weights(track_segment_id);

CREATE INDEX IF NOT EXISTS idx_template_segment_weights_ai_classification_id 
    ON template_segment_weights(ai_classification_id);

CREATE INDEX IF NOT EXISTS idx_template_segment_weights_weight 
    ON template_segment_weights(weight DESC);

-- 复合索引：按模板和片段查询权重配置
CREATE INDEX IF NOT EXISTS idx_template_segment_weights_template_segment 
    ON template_segment_weights(template_id, track_segment_id);

-- 复合索引：按模板、片段和权重排序查询
CREATE INDEX IF NOT EXISTS idx_template_segment_weights_template_segment_weight 
    ON template_segment_weights(template_id, track_segment_id, weight DESC);
