CREATE DATABASE IF NOT EXISTS `medical_consultation_agent`
  DEFAULT CHARACTER SET utf8mb4
  COLLATE utf8mb4_unicode_ci;

USE `medical_consultation_agent`;

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

DROP TABLE IF EXISTS `audit_logs`;
DROP TABLE IF EXISTS `user_learning_profiles`;
DROP TABLE IF EXISTS `training_record`;
DROP TABLE IF EXISTS `scoring_rule`;
DROP TABLE IF EXISTS `teaching_case`;
DROP TABLE IF EXISTS `traditional_case`;
DROP TABLE IF EXISTS `case_base`;
DROP TABLE IF EXISTS `rubric_templates`;
DROP TABLE IF EXISTS `prompt_templates`;
DROP TABLE IF EXISTS `knowledge_chunks`;
DROP TABLE IF EXISTS `knowledge_documents`;
DROP TABLE IF EXISTS `knowledge_sources`;
DROP TABLE IF EXISTS `evaluation_report_exports`;
DROP TABLE IF EXISTS `evaluation_records`;
DROP TABLE IF EXISTS `session_submissions`;
DROP TABLE IF EXISTS `session_orders`;
DROP TABLE IF EXISTS `session_runtime_messages`;
DROP TABLE IF EXISTS `training_sessions`;
DROP TABLE IF EXISTS `case_exam_items`;
DROP TABLE IF EXISTS `cases`;
DROP TABLE IF EXISTS `users`;
DROP TABLE IF EXISTS `departments`;

CREATE TABLE `departments` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '科室ID',
  `name` varchar(100) NOT NULL COMMENT '科室名称',
  `code` varchar(50) NOT NULL COMMENT '科室编码',
  `parent_id` int(11) DEFAULT NULL COMMENT '父级科室ID',
  `sort_order` int(11) DEFAULT 0 COMMENT '排序',
  `is_active` tinyint(1) DEFAULT 1 COMMENT '是否激活',
  `created_at` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_department_code` (`code`),
  KEY `idx_department_parent` (`parent_id`),
  CONSTRAINT `fk_department_parent` FOREIGN KEY (`parent_id`) REFERENCES `departments` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='科室表';

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '内部占位用户ID',
  `external_user_id` varchar(128) NOT NULL COMMENT '宿主系统用户ID',
  `display_name` varchar(100) DEFAULT NULL COMMENT '展示名',
  `created_at` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_external_user_id` (`external_user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='宿主用户引用占位表';

CREATE TABLE `case_base` (
  `id` bigint NOT NULL AUTO_INCREMENT COMMENT '源库病例主表ID',
  `title` varchar(255) NOT NULL COMMENT '病例标题',
  `case_type` varchar(30) NOT NULL COMMENT '病例分类/训练类别',
  `difficulty` varchar(20) NOT NULL DEFAULT 'medium' COMMENT '难度',
  `difficulty_score` int DEFAULT NULL COMMENT '难度分值',
  `chief_complaint` longtext NOT NULL COMMENT '主诉',
  `description` longtext NOT NULL COMMENT '病例描述',
  `patient_age` int DEFAULT NULL COMMENT '患者年龄',
  `patient_gender` varchar(10) NOT NULL COMMENT '患者性别',
  `tags` varchar(500) NOT NULL DEFAULT '' COMMENT '标签',
  `symptom_tags` json NOT NULL COMMENT '症状标签',
  `disease_tags` json NOT NULL COMMENT '疾病标签',
  `competency_tags` json NOT NULL COMMENT '能力标签',
  `guideline_tags` json NOT NULL COMMENT '指南标签',
  `knowledge_points` json NOT NULL COMMENT '知识点',
  `icd_codes` varchar(500) NOT NULL DEFAULT '' COMMENT 'ICD编码',
  `estimated_minutes` int DEFAULT NULL COMMENT '预计训练时长',
  `osce_enabled` tinyint(1) NOT NULL DEFAULT 0 COMMENT '是否OSCE',
  `rag_enabled` tinyint(1) NOT NULL DEFAULT 0 COMMENT '是否启用指南检索',
  `ai_prompt_template` longtext NOT NULL COMMENT 'AI病人提示词模板引用',
  `multimodal_assets` json NOT NULL COMMENT '多模态资源',
  `vector_status` smallint NOT NULL DEFAULT 0 COMMENT '向量状态',
  `publish_status` smallint NOT NULL DEFAULT 1 COMMENT '发布状态',
  `status` smallint NOT NULL DEFAULT 1 COMMENT '业务状态',
  `created_by_id` bigint DEFAULT NULL COMMENT '创建人ID',
  `department_id` bigint DEFAULT NULL COMMENT '科室ID',
  `created_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) COMMENT '创建时间',
  `updated_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6) COMMENT '更新时间',
  PRIMARY KEY (`id`),
  KEY `idx_case_base_department` (`department_id`),
  KEY `idx_case_base_case_type` (`case_type`),
  KEY `idx_case_base_status` (`status`, `publish_status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='源库病例主表';

CREATE TABLE `traditional_case` (
  `id` bigint NOT NULL AUTO_INCREMENT COMMENT '传统病例ID',
  `standard_diagnosis` longtext NOT NULL COMMENT '标准诊断',
  `standard_treatment` longtext NOT NULL COMMENT '标准治疗',
  `guideline_reference` longtext NOT NULL COMMENT '指南参考',
  `case_id` bigint NOT NULL COMMENT '病例主表ID',
  `created_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) COMMENT '创建时间',
  `updated_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6) COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_traditional_case_id` (`case_id`),
  CONSTRAINT `fk_traditional_case_base` FOREIGN KEY (`case_id`) REFERENCES `case_base` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='传统病例扩展表';

CREATE TABLE `teaching_case` (
  `id` bigint NOT NULL AUTO_INCREMENT COMMENT '教学互动病例ID',
  `teaching_goal` longtext NOT NULL COMMENT '教学目标',
  `discussion_questions` longtext NOT NULL COMMENT '讨论问题',
  `teacher_guide` longtext NOT NULL COMMENT '教师引导',
  `scoring_focus` longtext NOT NULL COMMENT '评分重点',
  `case_id` bigint NOT NULL COMMENT '病例主表ID',
  `created_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) COMMENT '创建时间',
  `updated_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6) COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_teaching_case_id` (`case_id`),
  CONSTRAINT `fk_teaching_case_base` FOREIGN KEY (`case_id`) REFERENCES `case_base` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='教学互动病例扩展表';

CREATE TABLE `scoring_rule` (
  `id` bigint NOT NULL AUTO_INCREMENT COMMENT '评分规则ID',
  `dimension` varchar(50) NOT NULL COMMENT '评分维度',
  `competency_dimension` varchar(50) NOT NULL COMMENT '能力维度',
  `score_weight` decimal(5,2) NOT NULL COMMENT '分值/权重',
  `ai_auto_score` tinyint(1) NOT NULL DEFAULT 1 COMMENT '是否AI自动评分',
  `osce_dimension` tinyint(1) NOT NULL DEFAULT 0 COMMENT '是否OSCE维度',
  `scoring_standard` longtext NOT NULL COMMENT '评分标准',
  `rubric_json` json NOT NULL COMMENT '结构化评分细则',
  `case_id` bigint NOT NULL COMMENT '病例主表ID',
  `created_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) COMMENT '创建时间',
  `updated_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6) COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_scoring_rule_case_dimension` (`case_id`, `dimension`, `competency_dimension`),
  KEY `idx_scoring_rule_case` (`case_id`),
  CONSTRAINT `fk_scoring_rule_case_base` FOREIGN KEY (`case_id`) REFERENCES `case_base` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='源库评分规则表';

CREATE TABLE `cases` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '病例ID',
  `source_case_id` bigint DEFAULT NULL COMMENT '源库病例ID，对应 case_base.id',
  `case_code` varchar(64) NOT NULL COMMENT '病例编码',
  `department_id` int(11) NOT NULL COMMENT '所属科室ID',
  `title` varchar(100) NOT NULL COMMENT '病例标题',
  `difficulty` enum('easy','medium','hard') DEFAULT 'medium' COMMENT '难度',
  `patient_name` varchar(50) DEFAULT NULL COMMENT '患者姓名',
  `patient_age` int(11) DEFAULT NULL COMMENT '患者年龄',
  `patient_gender` enum('male','female') DEFAULT NULL COMMENT '患者性别',
  `patient_occupation` varchar(50) DEFAULT NULL COMMENT '职业',
  `chief_complaint` text COMMENT '主诉',
  `present_illness` text COMMENT '现病史',
  `past_history` text COMMENT '既往史',
  `personal_history` text COMMENT '个人史',
  `family_history` text COMMENT '家族史',
  `physical_exam` json DEFAULT NULL COMMENT '体格检查数据',
  `auxiliary_exam` json DEFAULT NULL COMMENT '辅助检查数据',
  `diagnosis_primary` text COMMENT '主要诊断',
  `diagnosis_differential` json DEFAULT NULL COMMENT '鉴别诊断列表',
  `diagnosis_basis` text COMMENT '诊断依据',
  `treatment_plan` json DEFAULT NULL COMMENT '治疗方案',
  `consultation_config` json DEFAULT NULL COMMENT '会诊配置',
  `inquiry_options` json DEFAULT NULL COMMENT '问诊选项（互动模式）',
  `knowledge_videos` json DEFAULT NULL COMMENT '知识点视频（互动模式）',
  `quiz_questions` json DEFAULT NULL COMMENT '教学题库（互动模式）',
  `key_symptoms` json DEFAULT NULL COMMENT '关键症状',
  `key_exams` json DEFAULT NULL COMMENT '关键检查',
  `key_points` json DEFAULT NULL COMMENT '考核要点',
  `evidence_reasoning_chain` json DEFAULT NULL COMMENT '诊断循证思维链',
  `assessment_config` json DEFAULT NULL COMMENT '评分与考核配置',
  `ai_patient_profile` json DEFAULT NULL COMMENT 'AI病人人设',
  `patient_opening` text COMMENT 'AI病人开场白',
  `hidden_patient_info` json DEFAULT NULL COMMENT '问到才回答的隐藏信息',
  `has_teaching_video` tinyint(1) DEFAULT 0 COMMENT '是否有教学视频',
  `has_knowledge_points` tinyint(1) DEFAULT 0 COMMENT '是否有知识点',
  `has_quiz` tinyint(1) DEFAULT 0 COMMENT '是否有教学题库',
  `source_pdf_name` varchar(255) DEFAULT NULL COMMENT '来源PDF名称',
  `supported_training_type` enum('case_analysis','diagnosis_treatment','consultation') DEFAULT 'case_analysis' COMMENT '支持的训练类别（单选）',
  `supported_mode` enum('free_chat','interactive') DEFAULT 'free_chat' COMMENT '支持的交互模式（单选）',
  `is_active` tinyint(1) DEFAULT 1 COMMENT '是否激活',
  `created_by` int(11) DEFAULT NULL COMMENT '创建人ID',
  `created_at` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_case_code` (`case_code`),
  KEY `idx_department_id` (`department_id`),
  KEY `idx_difficulty` (`difficulty`),
  KEY `idx_is_active` (`is_active`),
  KEY `idx_created_by` (`created_by`),
  KEY `idx_training_type` (`supported_training_type`),
  KEY `idx_mode` (`supported_mode`),
  KEY `idx_cases_source_case` (`source_case_id`),
  CONSTRAINT `fk_case_department` FOREIGN KEY (`department_id`) REFERENCES `departments` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `fk_case_creator` FOREIGN KEY (`created_by`) REFERENCES `users` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='病例表';

CREATE TABLE `case_exam_items` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '检查项目ID',
  `case_id` int(11) NOT NULL COMMENT '病例ID',
  `source_case_id` bigint DEFAULT NULL COMMENT '源库病例ID，用于后续从 case_base 直接读取检查项目',
  `item_code` varchar(64) NOT NULL COMMENT '项目编码',
  `item_name` varchar(128) NOT NULL COMMENT '项目名称',
  `item_type` enum('lab','imaging','physical_exam','vital_sign','other') NOT NULL COMMENT '项目类型',
  `category` varchar(64) DEFAULT NULL COMMENT '分类',
  `result_text` text NOT NULL COMMENT '结果文本',
  `result_structured` json DEFAULT NULL COMMENT '结构化结果',
  `is_key` tinyint(1) DEFAULT 0 COMMENT '是否关键检查',
  `is_abnormal` tinyint(1) DEFAULT 0 COMMENT '是否异常',
  `score_weight` decimal(5,2) DEFAULT 0.00 COMMENT '评分权重',
  `display_order` int(11) DEFAULT 0 COMMENT '展示顺序',
  `created_at` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_case_item_code` (`case_id`,`item_code`),
  KEY `idx_exam_case_type` (`case_id`,`item_type`),
  KEY `idx_case_exam_source_case` (`source_case_id`),
  CONSTRAINT `fk_exam_case` FOREIGN KEY (`case_id`) REFERENCES `cases` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='病例检查检验项目表';

CREATE TABLE `training_sessions` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '会话ID',
  `session_code` varchar(64) NOT NULL COMMENT '会话编码',
  `user_id` varchar(128) NOT NULL COMMENT '宿主系统用户ID',
  `tenant_id` varchar(128) DEFAULT NULL COMMENT '租户或项目ID',
  `class_id` varchar(128) DEFAULT NULL COMMENT '班级或课程ID',
  `entry_scene` varchar(64) DEFAULT NULL COMMENT '入口场景',
  `case_id` int(11) NOT NULL COMMENT '病例ID',
  `source_case_id` bigint DEFAULT NULL COMMENT '源库病例ID，保留 case_id 兼容旧运行表',
  `training_type` enum('case_analysis','diagnosis_treatment','consultation') NOT NULL COMMENT '训练类别',
  `mode` enum('novice','practice','teaching') NOT NULL COMMENT '训练模式',
  `score_type` enum('percentage','five_point') NOT NULL DEFAULT 'percentage' COMMENT '分数输出类型',
  `status` enum('created','inquiry','diagnosis','treatment','evaluating','completed','aborted') NOT NULL DEFAULT 'created' COMMENT '会话状态',
  `started_at` datetime DEFAULT NULL COMMENT '开始时间',
  `inquiry_completed_at` datetime DEFAULT NULL COMMENT '问诊完成时间',
  `completed_at` datetime DEFAULT NULL COMMENT '完成时间',
  `memory_key` varchar(128) DEFAULT NULL COMMENT '短期memory key',
  `metadata` json DEFAULT NULL COMMENT '扩展数据',
  `created_at` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_session_code` (`session_code`),
  KEY `idx_session_user_status` (`user_id`,`status`),
  KEY `idx_session_case` (`case_id`),
  KEY `idx_session_created` (`created_at`),
  KEY `idx_training_sessions_source_case` (`source_case_id`),
  CONSTRAINT `fk_session_case` FOREIGN KEY (`case_id`) REFERENCES `cases` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='训练会话表';

CREATE TABLE `session_runtime_messages` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '短期消息ID',
  `session_id` int(11) NOT NULL COMMENT '会话ID',
  `user_id` varchar(128) NOT NULL COMMENT '宿主系统用户ID',
  `role` enum('doctor','patient','system','tool') NOT NULL COMMENT '角色',
  `content` text NOT NULL COMMENT '消息内容',
  `content_structured` json DEFAULT NULL COMMENT '结构化内容',
  `sequence_no` int(11) NOT NULL COMMENT '会话内序号',
  `expires_at` datetime DEFAULT NULL COMMENT '过期时间',
  `created_at` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  PRIMARY KEY (`id`),
  KEY `idx_runtime_session_seq` (`session_id`,`sequence_no`),
  KEY `idx_runtime_expires` (`expires_at`),
  CONSTRAINT `fk_runtime_session` FOREIGN KEY (`session_id`) REFERENCES `training_sessions` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='短期会话消息调试表';

CREATE TABLE `session_orders` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '申请ID',
  `session_id` int(11) NOT NULL COMMENT '会话ID',
  `user_id` varchar(128) NOT NULL COMMENT '宿主系统用户ID',
  `case_exam_item_id` int(11) NOT NULL COMMENT '病例检查项目ID',
  `item_code` varchar(64) NOT NULL COMMENT '项目编码',
  `item_name` varchar(128) NOT NULL COMMENT '项目名称',
  `item_type` varchar(32) NOT NULL COMMENT '项目类型',
  `result_text` text NOT NULL COMMENT '结果文本',
  `result_structured` json DEFAULT NULL COMMENT '结构化结果',
  `is_key` tinyint(1) DEFAULT 0 COMMENT '是否关键检查',
  `is_abnormal` tinyint(1) DEFAULT 0 COMMENT '是否异常',
  `ordered_at` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '申请时间',
  PRIMARY KEY (`id`),
  KEY `idx_order_session` (`session_id`),
  KEY `idx_order_user_session` (`user_id`,`session_id`),
  CONSTRAINT `fk_order_session` FOREIGN KEY (`session_id`) REFERENCES `training_sessions` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `fk_order_exam_item` FOREIGN KEY (`case_exam_item_id`) REFERENCES `case_exam_items` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='会话检查检验申请表';

CREATE TABLE `session_submissions` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '提交ID',
  `session_id` int(11) NOT NULL COMMENT '会话ID',
  `user_id` varchar(128) NOT NULL COMMENT '宿主系统用户ID',
  `primary_diagnosis` text COMMENT '主要诊断',
  `differential_diagnoses` json DEFAULT NULL COMMENT '鉴别诊断',
  `diagnosis_basis` text COMMENT '诊断依据',
  `treatment_principle` text COMMENT '治疗原则',
  `treatment_measures` text COMMENT '治疗措施',
  `risk_plan` text COMMENT '风险预案',
  `communication` text COMMENT '沟通告知与健康教育',
  `follow_up` text COMMENT '随访计划',
  `diagnosis_submitted_at` datetime DEFAULT NULL COMMENT '诊断提交时间',
  `treatment_submitted_at` datetime DEFAULT NULL COMMENT '治疗提交时间',
  `created_at` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_submission_session` (`session_id`),
  KEY `idx_submission_user` (`user_id`),
  CONSTRAINT `fk_submission_session` FOREIGN KEY (`session_id`) REFERENCES `training_sessions` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='会话诊断治疗提交表';

CREATE TABLE `knowledge_sources` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '知识来源ID',
  `source_code` varchar(64) NOT NULL COMMENT '来源编码',
  `source_name` varchar(255) NOT NULL COMMENT '来源名称',
  `source_type` enum('national_standard','department_expert','exam_requirement','clinical_guideline','humanistic_care','other') NOT NULL COMMENT '来源类型',
  `authority_level` int(11) DEFAULT 1 COMMENT '权威等级',
  `is_active` tinyint(1) DEFAULT 1 COMMENT '是否启用',
  `created_at` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_source_code` (`source_code`),
  KEY `idx_source_type` (`source_type`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='知识来源表';

CREATE TABLE `knowledge_documents` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '知识文档ID',
  `source_id` int(11) NOT NULL COMMENT '来源ID',
  `department_id` int(11) DEFAULT NULL COMMENT '科室ID',
  `title` varchar(255) NOT NULL COMMENT '文档标题',
  `task_type` varchar(64) DEFAULT NULL COMMENT '任务类型',
  `summary` text COMMENT '摘要',
  `file_path` varchar(512) DEFAULT NULL COMMENT '文件路径',
  `is_active` tinyint(1) DEFAULT 1 COMMENT '是否启用',
  `created_at` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  KEY `idx_doc_source` (`source_id`),
  KEY `idx_doc_department_task` (`department_id`,`task_type`),
  CONSTRAINT `fk_doc_source` FOREIGN KEY (`source_id`) REFERENCES `knowledge_sources` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `fk_doc_department` FOREIGN KEY (`department_id`) REFERENCES `departments` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='知识文档表';

CREATE TABLE `knowledge_chunks` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '知识片段ID',
  `document_id` int(11) NOT NULL COMMENT '文档ID',
  `department_id` int(11) DEFAULT NULL COMMENT '科室ID',
  `task_type` varchar(64) DEFAULT NULL COMMENT '任务类型',
  `chunk_text` text NOT NULL COMMENT '片段内容',
  `keywords` json DEFAULT NULL COMMENT '关键词',
  `weight` decimal(5,2) DEFAULT 1.00 COMMENT '权重',
  `is_active` tinyint(1) DEFAULT 1 COMMENT '是否启用',
  `created_at` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  PRIMARY KEY (`id`),
  KEY `idx_chunk_doc` (`document_id`),
  KEY `idx_chunk_department_task` (`department_id`,`task_type`),
  FULLTEXT KEY `ft_chunk_text` (`chunk_text`),
  CONSTRAINT `fk_chunk_doc` FOREIGN KEY (`document_id`) REFERENCES `knowledge_documents` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `fk_chunk_department` FOREIGN KEY (`department_id`) REFERENCES `departments` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='知识片段表';

CREATE TABLE `evaluation_records` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '评价记录ID',
  `evaluation_code` varchar(64) NOT NULL COMMENT '评价记录编码',
  `session_id` int(11) NOT NULL COMMENT '会话ID',
  `user_id` varchar(128) NOT NULL COMMENT '宿主系统用户ID',
  `tenant_id` varchar(128) DEFAULT NULL COMMENT '租户或项目ID',
  `case_id` int(11) NOT NULL COMMENT '病例ID',
  `source_case_id` bigint DEFAULT NULL COMMENT '源库病例ID，保留 case_id 兼容旧报告表',
  `training_type` varchar(64) NOT NULL COMMENT '训练类别',
  `mode` varchar(64) NOT NULL COMMENT '训练模式',
  `score_type` enum('percentage','five_point') NOT NULL COMMENT '分数类型',
  `total_score` decimal(6,2) NOT NULL COMMENT '总分',
  `dimension_scores` json NOT NULL COMMENT '维度评分',
  `errors` json DEFAULT NULL COMMENT '错误分析',
  `improvement_plan` json DEFAULT NULL COMMENT '改进方案',
  `evidence_summary` json DEFAULT NULL COMMENT '评分依据摘要',
  `guideline_refs` json DEFAULT NULL COMMENT '参考指南来源',
  `overall_comment` text COMMENT '总体评价',
  `llm_model` varchar(100) DEFAULT NULL COMMENT 'LLM模型',
  `latency_metrics` json DEFAULT NULL COMMENT '耗时指标',
  `pdf_file_path` varchar(512) DEFAULT NULL COMMENT 'PDF报告路径',
  `status` enum('generated','exported','failed') DEFAULT 'generated' COMMENT '状态',
  `created_at` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_evaluation_code` (`evaluation_code`),
  UNIQUE KEY `uk_evaluation_session` (`session_id`),
  KEY `idx_eval_user_created` (`user_id`,`created_at`),
  KEY `idx_eval_case` (`case_id`),
  KEY `idx_eval_source_case` (`source_case_id`),
  CONSTRAINT `fk_eval_session` FOREIGN KEY (`session_id`) REFERENCES `training_sessions` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `fk_eval_case` FOREIGN KEY (`case_id`) REFERENCES `cases` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='AI评价记录表';

CREATE TABLE `evaluation_report_exports` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '导出记录ID',
  `evaluation_id` int(11) NOT NULL COMMENT '评价记录ID',
  `user_id` varchar(128) NOT NULL COMMENT '宿主系统用户ID',
  `file_path` varchar(512) NOT NULL COMMENT 'PDF文件路径',
  `file_name` varchar(255) NOT NULL COMMENT 'PDF文件名',
  `score_type` enum('percentage','five_point') NOT NULL COMMENT '分数类型',
  `export_status` enum('success','failed') DEFAULT 'success' COMMENT '导出状态',
  `exported_at` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '导出时间',
  PRIMARY KEY (`id`),
  KEY `idx_export_eval` (`evaluation_id`),
  KEY `idx_export_user` (`user_id`,`exported_at`),
  CONSTRAINT `fk_export_eval` FOREIGN KEY (`evaluation_id`) REFERENCES `evaluation_records` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='评价报告PDF导出记录表';

CREATE TABLE `prompt_templates` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '提示词模板ID',
  `template_code` varchar(64) NOT NULL COMMENT '模板编码',
  `agent_type` enum('patient','scoring','report','polish','hint','knowledge') NOT NULL COMMENT 'Agent类型',
  `scene` varchar(64) NOT NULL COMMENT '场景',
  `version_no` varchar(32) NOT NULL COMMENT '版本',
  `model_type` enum('fast','reason') NOT NULL COMMENT '模型类型',
  `output_format` enum('text','json') NOT NULL COMMENT '输出格式',
  `file_path` varchar(512) NOT NULL COMMENT 'Markdown文件路径',
  `is_active` tinyint(1) DEFAULT 1 COMMENT '是否启用',
  `created_at` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_prompt_code_version` (`template_code`,`version_no`),
  KEY `idx_prompt_agent_scene` (`agent_type`,`scene`,`is_active`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='提示词模板元数据表';

CREATE TABLE `rubric_templates` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '评分规则ID',
  `rubric_code` varchar(64) NOT NULL COMMENT '规则编码',
  `rubric_name` varchar(128) NOT NULL COMMENT '规则名称',
  `version_no` varchar(32) NOT NULL COMMENT '版本',
  `department_id` int(11) DEFAULT NULL COMMENT '科室ID',
  `training_type` varchar(64) NOT NULL COMMENT '训练类别',
  `score_type` enum('percentage','five_point') NOT NULL COMMENT '分数类型',
  `dimensions` json NOT NULL COMMENT '评分维度',
  `is_active` tinyint(1) DEFAULT 1 COMMENT '是否启用',
  `created_at` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_rubric_code_version` (`rubric_code`,`version_no`),
  KEY `idx_rubric_department_type` (`department_id`,`training_type`,`score_type`),
  CONSTRAINT `fk_rubric_department` FOREIGN KEY (`department_id`) REFERENCES `departments` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='评分规则表';

CREATE TABLE `training_record` (
  `id` bigint NOT NULL AUTO_INCREMENT COMMENT '训练记录ID',
  `training_mode` varchar(50) NOT NULL COMMENT '训练模式：practice/teaching',
  `case_type` varchar(30) NOT NULL COMMENT '病例分类',
  `start_time` datetime(6) NOT NULL COMMENT '开始时间',
  `end_time` datetime(6) DEFAULT NULL COMMENT '结束时间',
  `duration_seconds` int DEFAULT NULL COMMENT '训练耗时秒',
  `total_score` decimal(5,2) DEFAULT NULL COMMENT '总分',
  `ai_score` decimal(5,2) DEFAULT NULL COMMENT 'AI评分',
  `teacher_score` decimal(5,2) DEFAULT NULL COMMENT '教师评分',
  `evaluation_level` varchar(20) NOT NULL DEFAULT '' COMMENT '评价等级',
  `status` varchar(30) NOT NULL COMMENT '记录状态',
  `feedback` longtext NOT NULL COMMENT '总体反馈',
  `thinking_chain` longtext NOT NULL COMMENT '评价证据链摘要',
  `diagnosis_path` longtext NOT NULL COMMENT '诊断路径摘要',
  `wrong_points` json NOT NULL COMMENT '错误点',
  `missed_questions` json NOT NULL COMMENT '遗漏问题',
  `recommendation_result` json NOT NULL COMMENT '改进建议',
  `ai_feedback_structured` json NOT NULL COMMENT 'AI结构化反馈',
  `osce_station_score` json NOT NULL COMMENT 'OSCE评分',
  `interruption_count` int NOT NULL DEFAULT 0 COMMENT '中断次数',
  `emotion_analysis` json NOT NULL COMMENT '情绪分析',
  `prompt_version` varchar(50) NOT NULL DEFAULT 'v1' COMMENT '提示词版本',
  `rag_context_version` varchar(50) NOT NULL DEFAULT 'none' COMMENT '指南检索版本',
  `case_id` bigint NOT NULL COMMENT '病例ID，对应 case_base.id',
  `teacher_id` bigint DEFAULT NULL COMMENT '教师ID',
  `user_id` bigint DEFAULT NULL COMMENT '源系统数字用户ID；宿主传字符串时为空',
  `external_user_id` varchar(128) NOT NULL COMMENT '宿主系统传入的 user_id',
  `session_id` bigint DEFAULT NULL COMMENT '本系统训练会话ID',
  `evaluation_record_id` bigint DEFAULT NULL COMMENT '兼容评价记录ID',
  `score_type` varchar(20) NOT NULL DEFAULT 'percentage' COMMENT '分数类型',
  `pdf_file_path` varchar(512) DEFAULT NULL COMMENT 'PDF报告路径',
  `created_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) COMMENT '创建时间',
  `updated_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6) COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_training_record_session` (`session_id`),
  KEY `idx_training_record_external_user` (`external_user_id`, `created_at`),
  KEY `idx_training_record_case` (`case_id`),
  KEY `idx_training_record_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='源库训练记录表';

CREATE TABLE `user_learning_profiles` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '学习档案ID',
  `user_id` varchar(128) NOT NULL COMMENT '宿主系统用户ID',
  `tenant_id` varchar(128) DEFAULT NULL COMMENT '租户或项目ID',
  `total_evaluations` int(11) DEFAULT 0 COMMENT '评价次数',
  `avg_score_percentage` decimal(6,2) DEFAULT NULL COMMENT '百分制平均分',
  `avg_score_five_point` decimal(4,2) DEFAULT NULL COMMENT '五分制平均分',
  `weak_dimensions` json DEFAULT NULL COMMENT '薄弱维度',
  `last_evaluation_id` int(11) DEFAULT NULL COMMENT '最近评价记录ID',
  `last_trained_at` datetime DEFAULT NULL COMMENT '最近训练时间',
  `created_at` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_profile_user_tenant` (`user_id`,`tenant_id`),
  KEY `idx_profile_last_trained` (`last_trained_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户学习档案表';

CREATE TABLE `audit_logs` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '审计日志ID',
  `user_id` varchar(128) DEFAULT NULL COMMENT '宿主系统用户ID',
  `tenant_id` varchar(128) DEFAULT NULL COMMENT '租户或项目ID',
  `session_id` int(11) DEFAULT NULL COMMENT '会话ID',
  `action` varchar(64) NOT NULL COMMENT '动作',
  `resource_type` varchar(64) NOT NULL COMMENT '资源类型',
  `resource_id` varchar(128) DEFAULT NULL COMMENT '资源ID',
  `request_id` varchar(128) DEFAULT NULL COMMENT '请求ID',
  `ip_address` varchar(64) DEFAULT NULL COMMENT 'IP地址',
  `user_agent` varchar(512) DEFAULT NULL COMMENT 'User-Agent',
  `metadata` json DEFAULT NULL COMMENT '元数据',
  `created_at` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  PRIMARY KEY (`id`),
  KEY `idx_audit_user_created` (`user_id`,`created_at`),
  KEY `idx_audit_session` (`session_id`),
  KEY `idx_audit_action_created` (`action`,`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='审计日志表';

SET FOREIGN_KEY_CHECKS = 1;
