-- 智能报告生成平台 - 数据库初始化脚本
-- 数据库名建议：post_eval_report
-- 适用于 MySQL

-- 创建数据库（可选）
-- CREATE DATABASE IF NOT EXISTS post_eval_report DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- USE post_eval_report;

-- 项目（统一：知识库 + 撰写）
-- uuid 由应用层生成，避免 MySQL 8/9 对生成列函数限制导致初始化失败
CREATE TABLE IF NOT EXISTS projects (
    id INT AUTO_INCREMENT PRIMARY KEY,
    uuid VARCHAR(32) NOT NULL UNIQUE,
    name VARCHAR(255) NOT NULL,
    description TEXT,
    created_at DATETIME NOT NULL,
    updated_at DATETIME NOT NULL,
    doc_count INT DEFAULT 0,
    eval_reports_count INT DEFAULT 0,
    total_size VARCHAR(32) DEFAULT '0 B',
    tags TEXT,
    status VARCHAR(16) DEFAULT 'active',
    color VARCHAR(16) DEFAULT '#3b82f6',
    sync_suppressed_table_names LONGTEXT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE INDEX idx_projects_created_at ON projects(created_at);
CREATE INDEX idx_projects_updated_at ON projects(updated_at);
CREATE INDEX idx_projects_status ON projects(status);

-- 知识库目录表：project_id 关联 projects.uuid；parent_id 形成目录树
CREATE TABLE IF NOT EXISTS kb_directories (
    id VARCHAR(64) PRIMARY KEY,
    project_id VARCHAR(32) NOT NULL,
    parent_id VARCHAR(64) NULL,
    name VARCHAR(255) NOT NULL,
    full_path VARCHAR(1024) NOT NULL,
    created_at DATETIME NOT NULL,
    updated_at DATETIME NOT NULL,
    FOREIGN KEY (project_id) REFERENCES projects(uuid) ON DELETE CASCADE,
    FOREIGN KEY (parent_id) REFERENCES kb_directories(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE INDEX idx_kb_dirs_project ON kb_directories(project_id);
CREATE INDEX idx_kb_dirs_parent ON kb_directories(parent_id);

-- 知识库文档（status: 0=失败 2=排队中 3=处理中 4=可用）
CREATE TABLE IF NOT EXISTS kb_documents (
    id VARCHAR(64) PRIMARY KEY,
    project_id VARCHAR(32) NOT NULL,
    directory_id VARCHAR(64) NULL,
    name VARCHAR(255) NOT NULL,
    size VARCHAR(32) NOT NULL,
    file_path VARCHAR(512),
    storage_rel_path VARCHAR(512) NULL COMMENT '项目内完整相对路径(含文件名)',
    word_count INT DEFAULT 0,
    uploaded_at DATETIME NOT NULL,
    status INT DEFAULT 2,
    error_message TEXT NULL,
    factor JSON NULL COMMENT '文档要素 JSON 数组',
    category VARCHAR(32) NULL DEFAULT NULL COMMENT '文件分类',
    FOREIGN KEY (project_id) REFERENCES projects(uuid) ON DELETE CASCADE,
    FOREIGN KEY (directory_id) REFERENCES kb_directories(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE INDEX idx_kb_docs_project ON kb_documents(project_id);
CREATE INDEX idx_kb_docs_directory ON kb_documents(directory_id);

-- 若已有 kb_documents 表，执行以下语句添加 word_count 字段：
-- ALTER TABLE kb_documents ADD COLUMN word_count INT DEFAULT 0 AFTER file_path;

-- 撰写文档（project_id 关联 projects.uuid，与 kb_documents 一致）
CREATE TABLE IF NOT EXISTS write_documents (
    id VARCHAR(64) PRIMARY KEY,
    project_id VARCHAR(32) NOT NULL,
    title VARCHAR(255) NOT NULL,
    content LONGTEXT,
    word_count INT DEFAULT 0,
    created_at DATETIME NOT NULL,
    updated_at DATETIME NOT NULL,
    status VARCHAR(16) DEFAULT 'draft',
    sort_order INT DEFAULT 0,
    FOREIGN KEY (project_id) REFERENCES projects(uuid) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE INDEX idx_write_docs_project ON write_documents(project_id);

-- 文档版本
CREATE TABLE IF NOT EXISTS doc_versions (
    id VARCHAR(64) PRIMARY KEY,
    document_id VARCHAR(64) NOT NULL,
    version VARCHAR(32) NOT NULL,
    content LONGTEXT NOT NULL,
    citation_payload LONGTEXT NULL,
    saved_at DATETIME NOT NULL,
    author VARCHAR(64) NOT NULL,
    note TEXT,
    FOREIGN KEY (document_id) REFERENCES write_documents(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE INDEX idx_versions_doc ON doc_versions(document_id);

-- 要素表定义（全局/时间）
CREATE TABLE IF NOT EXISTS element_tables (
    id VARCHAR(64) PRIMARY KEY,
    project_id VARCHAR(32) NOT NULL,
    table_type VARCHAR(32) NOT NULL,
    table_name VARCHAR(255) NOT NULL,
    year INT NULL,
    is_time_dimension TINYINT(1) DEFAULT 0,
    sort_order INT DEFAULT 0,
    sync_suppressed_row_keys LONGTEXT NULL,
    custom_row_order LONGTEXT NULL,
    created_at DATETIME NOT NULL,
    updated_at DATETIME NOT NULL,
    FOREIGN KEY (project_id) REFERENCES projects(uuid) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE INDEX idx_element_tables_project ON element_tables(project_id);
CREATE INDEX idx_element_tables_type_year ON element_tables(table_type, year);
CREATE INDEX idx_element_tables_name ON element_tables(table_name);

-- 要素单元格
CREATE TABLE IF NOT EXISTS element_cells (
    id VARCHAR(64) PRIMARY KEY,
    table_id VARCHAR(64) NOT NULL,
    project_id VARCHAR(32) NOT NULL,
    row_key VARCHAR(255) NOT NULL,
    col_key VARCHAR(255) NULL,
    year INT NULL,
    value LONGTEXT NULL,
    source_document_id VARCHAR(64) NULL,
    source_line_no INT NULL,
    source_line_end INT NULL,
    source_quote TEXT NULL,
    confidence FLOAT NULL,
    extraction_batch_id VARCHAR(64) NULL,
    extraction_model VARCHAR(128) NULL,
    source_type VARCHAR(16) NULL COMMENT 'extract=文档抽取, manual=手工输入',
    conflict_status VARCHAR(16) DEFAULT 'none',
    created_at DATETIME NOT NULL,
    updated_at DATETIME NOT NULL,
    FOREIGN KEY (table_id) REFERENCES element_tables(id) ON DELETE CASCADE,
    FOREIGN KEY (project_id) REFERENCES projects(uuid) ON DELETE CASCADE,
    FOREIGN KEY (source_document_id) REFERENCES kb_documents(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE INDEX idx_element_cells_project ON element_cells(project_id);
CREATE INDEX idx_element_cells_row_col ON element_cells(row_key, col_key);
CREATE INDEX idx_element_cells_year ON element_cells(year);

-- 抽取结果留存（table/element）
CREATE TABLE IF NOT EXISTS extraction_results (
    id VARCHAR(64) PRIMARY KEY,
    project_id VARCHAR(32) NOT NULL,
    document_id VARCHAR(64) NOT NULL,
    batch_id VARCHAR(64) NOT NULL,
    result_type VARCHAR(16) NOT NULL,
    table_type VARCHAR(32) NULL,
    table_name VARCHAR(255) NULL,
    year INT NULL,
    item_key VARCHAR(255) NOT NULL,
    item_value LONGTEXT NULL,
    source_line_no INT NULL,
    source_line_end INT NULL,
    confidence FLOAT NULL,
    raw_payload JSON NULL,
    extracted_at DATETIME NULL,
    created_at DATETIME NOT NULL,
    FOREIGN KEY (project_id) REFERENCES projects(uuid) ON DELETE CASCADE,
    FOREIGN KEY (document_id) REFERENCES kb_documents(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE INDEX idx_extraction_project_doc ON extraction_results(project_id, document_id);
CREATE INDEX idx_extraction_batch ON extraction_results(batch_id);
CREATE INDEX idx_extraction_table_name ON extraction_results(table_name);
CREATE INDEX idx_extraction_key ON extraction_results(item_key);

-- 要素抽取结果明细（面向“细则章节/小节提示词 -> 项目材料”）
CREATE TABLE IF NOT EXISTS element_extraction_results (
    id VARCHAR(64) PRIMARY KEY,
    project_id VARCHAR(32) NOT NULL,
    table_type VARCHAR(32) NOT NULL,
    year INT NULL,
    table_name VARCHAR(255) NOT NULL,
    extracted_at DATETIME NOT NULL,
    item_key VARCHAR(255) NOT NULL,
    item_value LONGTEXT NULL,
    source_document_id VARCHAR(64) NULL,
    source_line_no INT NULL,
    source_line_end INT NULL,
    created_at DATETIME NOT NULL,
    FOREIGN KEY (project_id) REFERENCES projects(uuid) ON DELETE CASCADE,
    FOREIGN KEY (source_document_id) REFERENCES kb_documents(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE INDEX idx_el_ext_project ON element_extraction_results(project_id);
CREATE INDEX idx_el_ext_table ON element_extraction_results(table_type, year, table_name);
CREATE INDEX idx_el_ext_key ON element_extraction_results(item_key);
CREATE INDEX idx_el_ext_source_doc ON element_extraction_results(source_document_id);

-- 冲突记录
CREATE TABLE IF NOT EXISTS element_conflicts (
    id VARCHAR(64) PRIMARY KEY,
    project_id VARCHAR(32) NOT NULL,
    table_id VARCHAR(64) NULL,
    cell_id VARCHAR(64) NULL,
    item_key VARCHAR(255) NOT NULL,
    old_value LONGTEXT NULL,
    new_value LONGTEXT NULL,
    selected_value LONGTEXT NULL,
    source_document_id VARCHAR(64) NULL,
    source_line_no INT NULL,
    status VARCHAR(16) DEFAULT 'pending',
    created_at DATETIME NOT NULL,
    updated_at DATETIME NOT NULL,
    FOREIGN KEY (project_id) REFERENCES projects(uuid) ON DELETE CASCADE,
    FOREIGN KEY (table_id) REFERENCES element_tables(id) ON DELETE SET NULL,
    FOREIGN KEY (cell_id) REFERENCES element_cells(id) ON DELETE SET NULL,
    FOREIGN KEY (source_document_id) REFERENCES kb_documents(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE INDEX idx_element_conflicts_project ON element_conflicts(project_id);
CREATE INDEX idx_element_conflicts_status ON element_conflicts(status);

-- 文档 markdown 落库
CREATE TABLE IF NOT EXISTS document_markdowns (
    id VARCHAR(64) PRIMARY KEY,
    project_id VARCHAR(32) NOT NULL,
    document_id VARCHAR(64) NOT NULL,
    extracted_filename VARCHAR(255) NULL,
    markdown_content LONGTEXT NOT NULL,
    content_hash VARCHAR(64) NULL,
    created_at DATETIME NOT NULL,
    updated_at DATETIME NOT NULL,
    FOREIGN KEY (project_id) REFERENCES projects(uuid) ON DELETE CASCADE,
    FOREIGN KEY (document_id) REFERENCES kb_documents(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE INDEX idx_markdowns_project_doc ON document_markdowns(project_id, document_id);

-- 文档段落切分
CREATE TABLE IF NOT EXISTS document_chunks (
    id VARCHAR(64) PRIMARY KEY,
    project_id VARCHAR(32) NOT NULL,
    document_id VARCHAR(64) NOT NULL,
    markdown_id VARCHAR(64) NULL,
    heading VARCHAR(512) NULL,
    chunk_text LONGTEXT NOT NULL,
    chunk_index INT DEFAULT 0,
    source_line_start INT NULL,
    source_line_end INT NULL,
    vector_id VARCHAR(128) NULL,
    created_at DATETIME NOT NULL,
    FOREIGN KEY (project_id) REFERENCES projects(uuid) ON DELETE CASCADE,
    FOREIGN KEY (document_id) REFERENCES kb_documents(id) ON DELETE CASCADE,
    FOREIGN KEY (markdown_id) REFERENCES document_markdowns(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE INDEX idx_chunks_project_doc ON document_chunks(project_id, document_id);
CREATE INDEX idx_chunks_heading ON document_chunks(heading(255));

-- 独立后台任务：pdf2md 文件处理与 element-agent 要素抽取
CREATE TABLE IF NOT EXISTS tasks (
    id VARCHAR(64) PRIMARY KEY,
    project VARCHAR(64) NOT NULL,
    task_type INT NOT NULL,
    file_id VARCHAR(64) NULL,
    file_path VARCHAR(1024) NULL,
    status INT NOT NULL DEFAULT 1,
    payload_json JSON NULL,
    result_path VARCHAR(1024) NULL,
    error_message LONGTEXT NULL,
    add_time DATETIME NOT NULL,
    finish_time DATETIME NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE INDEX idx_tasks_status_type_time ON tasks(status, task_type, add_time);
CREATE INDEX idx_tasks_project ON tasks(project);
CREATE INDEX idx_tasks_file_id ON tasks(file_id);

-- 模板管理
CREATE TABLE IF NOT EXISTS report_templates (
    id VARCHAR(64) PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    description TEXT NULL,
    is_default TINYINT(1) DEFAULT 0,
    is_active TINYINT(1) DEFAULT 1,
    created_at DATETIME NOT NULL,
    updated_at DATETIME NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE INDEX idx_templates_default ON report_templates(is_default);

CREATE TABLE IF NOT EXISTS report_template_sections (
    id VARCHAR(64) PRIMARY KEY,
    template_id VARCHAR(64) NOT NULL,
    section_key VARCHAR(64) NOT NULL,
    section_title VARCHAR(255) NOT NULL,
    section_prompt LONGTEXT NULL,
    section_output_contract LONGTEXT NULL,
    section_order INT DEFAULT 0,
    examples LONGTEXT NULL,
    created_at DATETIME NOT NULL,
    updated_at DATETIME NOT NULL,
    FOREIGN KEY (template_id) REFERENCES report_templates(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE INDEX idx_template_sections_template ON report_template_sections(template_id);

-- 报告生成任务（7章分章异步）
CREATE TABLE IF NOT EXISTS report_generation_jobs (
    id VARCHAR(64) PRIMARY KEY,
    project_id VARCHAR(32) NOT NULL,
    template_id VARCHAR(64) NULL,
    status VARCHAR(16) DEFAULT 'pending',
    progress INT DEFAULT 0,
    current_section_key VARCHAR(64) NULL,
    error_message TEXT NULL,
    requested_by VARCHAR(64) NULL,
    options JSON NULL,
    snapshot JSON NULL,
    created_at DATETIME NOT NULL,
    updated_at DATETIME NOT NULL,
    completed_at DATETIME NULL,
    FOREIGN KEY (project_id) REFERENCES projects(uuid) ON DELETE CASCADE,
    FOREIGN KEY (template_id) REFERENCES report_templates(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE INDEX idx_report_jobs_project ON report_generation_jobs(project_id);
CREATE INDEX idx_report_jobs_status ON report_generation_jobs(status);

CREATE TABLE IF NOT EXISTS report_generation_chapters (
    id VARCHAR(64) PRIMARY KEY,
    job_id VARCHAR(64) NOT NULL,
    section_key VARCHAR(64) NOT NULL,
    section_title VARCHAR(255) NOT NULL,
    section_order INT DEFAULT 0,
    status VARCHAR(16) DEFAULT 'pending',
    content LONGTEXT NULL,
    prompt_text LONGTEXT NULL,
    evidence_payload JSON NULL,
    validation_payload JSON NULL,
    error_message TEXT NULL,
    created_at DATETIME NOT NULL,
    updated_at DATETIME NOT NULL,
    completed_at DATETIME NULL,
    FOREIGN KEY (job_id) REFERENCES report_generation_jobs(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE INDEX idx_report_chapters_job ON report_generation_chapters(job_id);
CREATE INDEX idx_report_chapters_status ON report_generation_chapters(status);

-- 最小 RBAC
CREATE TABLE IF NOT EXISTS departments (
    id VARCHAR(64) PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    description TEXT NULL,
    parent_id VARCHAR(64) NULL,
    created_at DATETIME NOT NULL,
    updated_at DATETIME NOT NULL,
    FOREIGN KEY (parent_id) REFERENCES departments(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS users (
    id VARCHAR(64) PRIMARY KEY,
    username VARCHAR(64) NOT NULL UNIQUE,
    password_hash VARCHAR(255) NULL,
    department_id VARCHAR(64) NULL,
    created_at DATETIME NOT NULL,
    updated_at DATETIME NOT NULL,
    FOREIGN KEY (department_id) REFERENCES departments(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE INDEX idx_users_department ON users(department_id);

CREATE TABLE IF NOT EXISTS roles (
    id VARCHAR(64) PRIMARY KEY,
    name VARCHAR(64) NOT NULL UNIQUE,
    description TEXT NULL,
    created_at DATETIME NOT NULL,
    updated_at DATETIME NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS permissions (
    id VARCHAR(64) PRIMARY KEY,
    perm_key VARCHAR(128) NOT NULL UNIQUE,
    perm_type VARCHAR(32) NOT NULL,
    description TEXT NULL,
    created_at DATETIME NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE INDEX idx_permissions_type ON permissions(perm_type);

CREATE TABLE IF NOT EXISTS role_permissions (
    id VARCHAR(64) PRIMARY KEY,
    role_id VARCHAR(64) NOT NULL,
    permission_id VARCHAR(64) NOT NULL,
    created_at DATETIME NOT NULL,
    FOREIGN KEY (role_id) REFERENCES roles(id) ON DELETE CASCADE,
    FOREIGN KEY (permission_id) REFERENCES permissions(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS user_roles (
    id VARCHAR(64) PRIMARY KEY,
    user_id VARCHAR(64) NOT NULL,
    role_id VARCHAR(64) NOT NULL,
    created_at DATETIME NOT NULL,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    FOREIGN KEY (role_id) REFERENCES roles(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS project_members (
    id VARCHAR(64) PRIMARY KEY,
    project_id VARCHAR(32) NOT NULL,
    user_id VARCHAR(64) NOT NULL,
    role VARCHAR(32) DEFAULT 'editor',
    created_at DATETIME NOT NULL,
    FOREIGN KEY (project_id) REFERENCES projects(uuid) ON DELETE CASCADE,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE INDEX idx_project_members_project ON project_members(project_id);

CREATE TABLE IF NOT EXISTS project_departments (
    id VARCHAR(64) PRIMARY KEY,
    project_id VARCHAR(32) NOT NULL,
    department_id VARCHAR(64) NOT NULL,
    created_at DATETIME NOT NULL,
    FOREIGN KEY (project_id) REFERENCES projects(uuid) ON DELETE CASCADE,
    FOREIGN KEY (department_id) REFERENCES departments(id) ON DELETE CASCADE,
    UNIQUE KEY uq_project_department (project_id, department_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE INDEX idx_project_departments_project ON project_departments(project_id);

-- 回填记录：每次要素回填均留痕，支持证据追溯
CREATE TABLE IF NOT EXISTS fill_records (
    id VARCHAR(64) PRIMARY KEY,
    project_id VARCHAR(32) NOT NULL,
    cell_id VARCHAR(64) NULL,
    table_id VARCHAR(64) NULL,
    row_key VARCHAR(255) NOT NULL,
    col_key VARCHAR(255) NULL,
    year INT NULL,
    filled_value LONGTEXT NULL,
    previous_value LONGTEXT NULL,
    source_document_id VARCHAR(64) NULL,
    source_document_name VARCHAR(255) NULL COMMENT '冗余存储文档名，文档删除后仍可追溯',
    source_line_no INT NULL,
    source_line_end INT NULL,
    source_quote TEXT NULL COMMENT '原文摘录片段，作为回填依据',
    confidence FLOAT NULL,
    extraction_batch_id VARCHAR(64) NULL,
    extraction_model VARCHAR(128) NULL COMMENT '使用的 LLM 模型标识',
    fill_type VARCHAR(16) NOT NULL DEFAULT 'auto' COMMENT 'auto=抽取回填, manual=人工编辑, resolve=冲突解决',
    created_at DATETIME NOT NULL,
    FOREIGN KEY (project_id) REFERENCES projects(uuid) ON DELETE CASCADE,
    FOREIGN KEY (cell_id) REFERENCES element_cells(id) ON DELETE SET NULL,
    FOREIGN KEY (table_id) REFERENCES element_tables(id) ON DELETE SET NULL,
    FOREIGN KEY (source_document_id) REFERENCES kb_documents(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE INDEX idx_fill_records_project ON fill_records(project_id);
CREATE INDEX idx_fill_records_cell ON fill_records(cell_id);
CREATE INDEX idx_fill_records_batch ON fill_records(extraction_batch_id);
CREATE INDEX idx_fill_records_source_doc ON fill_records(source_document_id);
CREATE INDEX idx_fill_records_created ON fill_records(created_at);

-- ============================================================
-- report_section_references：章节参考范文
-- ============================================================
CREATE TABLE IF NOT EXISTS report_section_references (
    id VARCHAR(64) PRIMARY KEY,
    template_id VARCHAR(64) NULL COMMENT '关联模板ID（report_templates.id），按模板过滤参考范文',
    source_file VARCHAR(255) NOT NULL COMMENT '来源文件名',
    section_key VARCHAR(64) NOT NULL COMMENT '章节标识，如 1.1、2.1.1',
    section_title VARCHAR(255) NOT NULL COMMENT '章节标题',
    section_order INT DEFAULT 0 COMMENT '章节序号',
    content TEXT NOT NULL COMMENT '该章节的参考范文 Markdown',
    created_at DATETIME NOT NULL,
    updated_at DATETIME NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE INDEX idx_ref_source_file ON report_section_references(source_file);
CREATE INDEX idx_ref_section_key ON report_section_references(section_key);
CREATE INDEX idx_ref_template_id ON report_section_references(template_id);
