-- ==============================================================================
-- MCP Server 题目管理与检索系统 - 数据库初始化脚本
-- ==============================================================================
-- 
-- 数据库：SQLite
-- 用途：存储题目完整元数据、标签信息和关联关系
-- 版本：1.0.0
-- 
-- ==============================================================================

-- ------------------------------------------------------------------------------
-- 1. 题目表（questions）
-- ------------------------------------------------------------------------------

CREATE TABLE IF NOT EXISTS questions (
    -- 主键
    question_id TEXT PRIMARY KEY NOT NULL,
    
    -- 基本信息
    title TEXT NOT NULL CHECK(length(title) > 0 AND length(title) <= 200),
    content TEXT NOT NULL CHECK(length(content) > 0 AND length(content) <= 10000),
    question_type TEXT NOT NULL CHECK(question_type IN ('单选', '多选', '判断', '填空', '简答')),
    category TEXT NOT NULL CHECK(length(category) > 0),
    difficulty TEXT NOT NULL CHECK(difficulty IN ('简单', '中等', '困难')),
    status TEXT NOT NULL DEFAULT '草稿' CHECK(status IN ('草稿', '已发布', '已归档')),
    
    -- 答案相关
    answer TEXT,
    explanation TEXT,
    
    -- 来源信息
    source TEXT,
    source_url TEXT,
    
    -- 分值和统计
    points INTEGER CHECK(points >= 0),
    usage_count INTEGER NOT NULL DEFAULT 0 CHECK(usage_count >= 0),
    correct_rate REAL CHECK(correct_rate IS NULL OR (correct_rate >= 0.0 AND correct_rate <= 1.0)),
    
    -- 时间戳
    created_at TEXT NOT NULL,
    updated_at TEXT NOT NULL,
    created_by TEXT
);

-- 题目表索引
CREATE INDEX IF NOT EXISTS idx_questions_category ON questions(category);
CREATE INDEX IF NOT EXISTS idx_questions_difficulty ON questions(difficulty);
CREATE INDEX IF NOT EXISTS idx_questions_status ON questions(status);
CREATE INDEX IF NOT EXISTS idx_questions_question_type ON questions(question_type);
CREATE INDEX IF NOT EXISTS idx_questions_created_at ON questions(created_at);
CREATE INDEX IF NOT EXISTS idx_questions_updated_at ON questions(updated_at);

-- 复合索引（用于常见查询组合）
CREATE INDEX IF NOT EXISTS idx_questions_category_status ON questions(category, status);
CREATE INDEX IF NOT EXISTS idx_questions_difficulty_status ON questions(difficulty, status);


-- ------------------------------------------------------------------------------
-- 2. 标签表（tags）
-- ------------------------------------------------------------------------------

CREATE TABLE IF NOT EXISTS tags (
    -- 主键（自增）
    tag_id INTEGER PRIMARY KEY AUTOINCREMENT,
    
    -- 标签名称（唯一）
    tag_name TEXT NOT NULL UNIQUE CHECK(length(tag_name) > 0 AND length(tag_name) <= 50),
    
    -- 使用次数
    usage_count INTEGER NOT NULL DEFAULT 0 CHECK(usage_count >= 0)
);

-- 标签表索引
CREATE INDEX IF NOT EXISTS idx_tags_name ON tags(tag_name);
CREATE INDEX IF NOT EXISTS idx_tags_usage_count ON tags(usage_count DESC);


-- ------------------------------------------------------------------------------
-- 3. 题目-标签关联表（question_tags）
-- ------------------------------------------------------------------------------

CREATE TABLE IF NOT EXISTS question_tags (
    -- 复合主键
    question_id TEXT NOT NULL,
    tag_id INTEGER NOT NULL,
    
    -- 外键约束
    FOREIGN KEY (question_id) REFERENCES questions(question_id) ON DELETE CASCADE,
    FOREIGN KEY (tag_id) REFERENCES tags(tag_id) ON DELETE CASCADE,
    
    -- 联合主键（防止重复关联）
    PRIMARY KEY (question_id, tag_id)
);

-- 关联表索引
CREATE INDEX IF NOT EXISTS idx_question_tags_question ON question_tags(question_id);
CREATE INDEX IF NOT EXISTS idx_question_tags_tag ON question_tags(tag_id);


-- ------------------------------------------------------------------------------
-- 4. 视图：题目完整信息（包含标签）
-- ------------------------------------------------------------------------------

CREATE VIEW IF NOT EXISTS v_questions_with_tags AS
SELECT 
    q.*,
    GROUP_CONCAT(t.tag_name, ',') AS tags
FROM questions q
LEFT JOIN question_tags qt ON q.question_id = qt.question_id
LEFT JOIN tags t ON qt.tag_id = t.tag_id
GROUP BY q.question_id;


-- ------------------------------------------------------------------------------
-- 5. 触发器：自动更新标签使用次数
-- ------------------------------------------------------------------------------

-- 添加题目-标签关联时，增加标签使用次数
CREATE TRIGGER IF NOT EXISTS trg_question_tags_insert
AFTER INSERT ON question_tags
FOR EACH ROW
BEGIN
    UPDATE tags 
    SET usage_count = usage_count + 1 
    WHERE tag_id = NEW.tag_id;
END;

-- 删除题目-标签关联时，减少标签使用次数
CREATE TRIGGER IF NOT EXISTS trg_question_tags_delete
AFTER DELETE ON question_tags
FOR EACH ROW
BEGIN
    UPDATE tags 
    SET usage_count = usage_count - 1 
    WHERE tag_id = OLD.tag_id;
END;

-- 删除题目时，自动清理孤立标签（使用次数为0的标签）
CREATE TRIGGER IF NOT EXISTS trg_questions_delete
AFTER DELETE ON questions
FOR EACH ROW
BEGIN
    DELETE FROM tags WHERE usage_count = 0;
END;


-- ------------------------------------------------------------------------------
-- 6. 数据完整性检查视图
-- ------------------------------------------------------------------------------

-- 检查数据一致性的视图
CREATE VIEW IF NOT EXISTS v_data_integrity_check AS
SELECT 
    'Total Questions' AS check_name,
    COUNT(*) AS count
FROM questions
UNION ALL
SELECT 
    'Total Tags' AS check_name,
    COUNT(*) AS count
FROM tags
UNION ALL
SELECT 
    'Total Associations' AS check_name,
    COUNT(*) AS count
FROM question_tags
UNION ALL
SELECT 
    'Orphaned Tags (usage_count=0)' AS check_name,
    COUNT(*) AS count
FROM tags 
WHERE usage_count = 0
UNION ALL
SELECT 
    'Published Questions' AS check_name,
    COUNT(*) AS count
FROM questions 
WHERE status = '已发布'
UNION ALL
SELECT 
    'Draft Questions' AS check_name,
    COUNT(*) AS count
FROM questions 
WHERE status = '草稿';


-- ------------------------------------------------------------------------------
-- 7. 统计查询视图
-- ------------------------------------------------------------------------------

-- 按分类统计
CREATE VIEW IF NOT EXISTS v_stats_by_category AS
SELECT 
    category,
    COUNT(*) AS total_count,
    SUM(CASE WHEN status = '已发布' THEN 1 ELSE 0 END) AS published_count,
    SUM(CASE WHEN difficulty = '简单' THEN 1 ELSE 0 END) AS easy_count,
    SUM(CASE WHEN difficulty = '中等' THEN 1 ELSE 0 END) AS medium_count,
    SUM(CASE WHEN difficulty = '困难' THEN 1 ELSE 0 END) AS hard_count,
    AVG(CASE WHEN usage_count > 0 THEN usage_count ELSE NULL END) AS avg_usage_count,
    AVG(CASE WHEN correct_rate IS NOT NULL THEN correct_rate ELSE NULL END) AS avg_correct_rate
FROM questions
GROUP BY category;

-- 按难度统计
CREATE VIEW IF NOT EXISTS v_stats_by_difficulty AS
SELECT 
    difficulty,
    COUNT(*) AS total_count,
    SUM(CASE WHEN status = '已发布' THEN 1 ELSE 0 END) AS published_count,
    AVG(CASE WHEN usage_count > 0 THEN usage_count ELSE NULL END) AS avg_usage_count,
    AVG(CASE WHEN correct_rate IS NOT NULL THEN correct_rate ELSE NULL END) AS avg_correct_rate
FROM questions
GROUP BY difficulty;

-- 按题型统计
CREATE VIEW IF NOT EXISTS v_stats_by_type AS
SELECT 
    question_type,
    COUNT(*) AS total_count,
    SUM(CASE WHEN status = '已发布' THEN 1 ELSE 0 END) AS published_count,
    AVG(CASE WHEN usage_count > 0 THEN usage_count ELSE NULL END) AS avg_usage_count
FROM questions
GROUP BY question_type;


-- ------------------------------------------------------------------------------
-- 8. 初始化完成标记
-- ------------------------------------------------------------------------------

-- 创建元数据表记录数据库版本
CREATE TABLE IF NOT EXISTS db_metadata (
    key TEXT PRIMARY KEY NOT NULL,
    value TEXT NOT NULL,
    updated_at TEXT NOT NULL
);

-- 插入数据库版本信息
INSERT OR REPLACE INTO db_metadata (key, value, updated_at) 
VALUES ('schema_version', '1.0.0', datetime('now'));

INSERT OR REPLACE INTO db_metadata (key, value, updated_at) 
VALUES ('initialized_at', datetime('now'), datetime('now'));


-- ------------------------------------------------------------------------------
-- 9. 全文检索表（FTS5）- 用于关键词检索
-- ------------------------------------------------------------------------------

-- 删除已存在的FTS表（如果存在）
DROP TABLE IF EXISTS questions_fts;

-- 创建FTS5虚拟表，支持中文全文检索
-- 使用contentless模式，直接存储数据
CREATE VIRTUAL TABLE questions_fts
USING fts5(
    question_id,
    title,
    content,
    tags,
    category,
    question_type,
    tokenize='unicode61 remove_diacritics 1'
);

-- 初始化FTS表（将现有数据插入）
INSERT INTO questions_fts(question_id, title, content, tags, category, question_type)
SELECT
    q.question_id,
    q.title,
    q.content,
    COALESCE(GROUP_CONCAT(t.tag_name, ','), '') as tags,
    q.category,
    q.question_type
FROM questions q
LEFT JOIN question_tags qt ON q.question_id = qt.question_id
LEFT JOIN tags t ON qt.tag_id = t.tag_id
GROUP BY q.question_id;

-- 创建触发器：插入题目时同步到FTS表
CREATE TRIGGER IF NOT EXISTS trg_questions_fts_insert
AFTER INSERT ON questions
FOR EACH ROW
BEGIN
    INSERT INTO questions_fts(question_id, title, content, tags, category, question_type)
    VALUES (
        NEW.question_id,
        NEW.title,
        NEW.content,
        (
            SELECT GROUP_CONCAT(t.tag_name, ',')
            FROM question_tags qt
            JOIN tags t ON qt.tag_id = t.tag_id
            WHERE qt.question_id = NEW.question_id
        ),
        NEW.category,
        NEW.question_type
    );
END;

-- 创建触发器：更新题目时同步到FTS表
CREATE TRIGGER IF NOT EXISTS trg_questions_fts_update
AFTER UPDATE ON questions
FOR EACH ROW
BEGIN
    DELETE FROM questions_fts WHERE question_id = NEW.question_id;
    INSERT INTO questions_fts(question_id, title, content, tags, category, question_type)
    VALUES (
        NEW.question_id,
        NEW.title,
        NEW.content,
        (
            SELECT GROUP_CONCAT(t.tag_name, ',')
            FROM question_tags qt
            JOIN tags t ON qt.tag_id = t.tag_id
            WHERE qt.question_id = NEW.question_id
        ),
        NEW.category,
        NEW.question_type
    );
END;

-- 创建触发器：删除题目时从FTS表删除
CREATE TRIGGER IF NOT EXISTS trg_questions_fts_delete
AFTER DELETE ON questions
FOR EACH ROW
BEGIN
    DELETE FROM questions_fts WHERE question_id = OLD.question_id;
END;

-- 创建触发器：标签变更时更新FTS表
CREATE TRIGGER IF NOT EXISTS trg_question_tags_update_fts
AFTER INSERT ON question_tags
FOR EACH ROW
BEGIN
    DELETE FROM questions_fts WHERE question_id = NEW.question_id;
    INSERT INTO questions_fts(question_id, title, content, tags, category, question_type)
    SELECT
        q.question_id,
        q.title,
        q.content,
        GROUP_CONCAT(t.tag_name, ','),
        q.category,
        q.question_type
    FROM questions q
    JOIN question_tags qt ON q.question_id = qt.question_id
    JOIN tags t ON qt.tag_id = t.tag_id
    WHERE q.question_id = NEW.question_id
    GROUP BY q.question_id;
END;

CREATE TRIGGER IF NOT EXISTS trg_question_tags_delete_fts
AFTER DELETE ON question_tags
FOR EACH ROW
BEGIN
    DELETE FROM questions_fts WHERE question_id = OLD.question_id;
    INSERT INTO questions_fts(question_id, title, content, tags, category, question_type)
    SELECT
        q.question_id,
        q.title,
        q.content,
        COALESCE(GROUP_CONCAT(t.tag_name, ','), ''),
        q.category,
        q.question_type
    FROM questions q
    LEFT JOIN question_tags qt ON q.question_id = qt.question_id
    LEFT JOIN tags t ON qt.tag_id = t.tag_id
    WHERE q.question_id = OLD.question_id
    GROUP BY q.question_id;
END;


-- ==============================================================================
-- 初始化脚本执行完成
-- ==============================================================================
--
-- 已创建的表：
-- - questions：题目表
-- - tags：标签表
-- - question_tags：题目-标签关联表
-- - db_metadata：数据库元数据表
-- - questions_fts：全文检索表（FTS5）
--
-- 已创建的视图：
-- - v_questions_with_tags：题目完整信息（含标签）
-- - v_data_integrity_check：数据完整性检查
-- - v_stats_by_category：按分类统计
-- - v_stats_by_difficulty：按难度统计
-- - v_stats_by_type：按题型统计
--
-- 已创建的触发器：
-- - trg_question_tags_insert：自动增加标签使用次数
-- - trg_question_tags_delete：自动减少标签使用次数
-- - trg_questions_delete：自动清理孤立标签
-- - trg_questions_fts_insert：FTS表同步插入
-- - trg_questions_fts_update：FTS表同步更新
-- - trg_questions_fts_delete：FTS表同步删除
-- - trg_question_tags_update_fts：标签变更时更新FTS表
-- - trg_question_tags_delete_fts：标签删除时更新FTS表
--
-- ==============================================================================
