-- find_agent 视频发现持久化表
-- MySQL 5.7+ / 8.0+
-- 与 supply_infra/db/models/video_discovery.py 保持一致。

SET NAMES utf8mb4;

CREATE TABLE IF NOT EXISTS `video_discovery_run` (
  `id` BIGINT NOT NULL AUTO_INCREMENT,
  `run_id` VARCHAR(64) NOT NULL COMMENT 'Agent 运行标识',
  `biz_dt` VARCHAR(32) NULL COMMENT '业务日 YYYYMMDD',
  `demand_grade_id` BIGINT NULL COMMENT '可选 demand_grade.id',
  `demand_word` VARCHAR(256) NOT NULL COMMENT '用户给定需求词',
  `seed_video_id` VARCHAR(64) NULL COMMENT '参考视频 id',
  `seed_video_title` VARCHAR(512) NULL COMMENT '参考视频标题',
  `relevant_points_json` TEXT NOT NULL COMMENT '与需求相关的视频点位 JSON',
  `intent_summary` TEXT NULL COMMENT 'Agent 对真实内容意图的解释',
  `status` VARCHAR(24) NOT NULL DEFAULT 'running'
    COMMENT 'running / finished / failed',
  `search_count` INT NOT NULL DEFAULT 0 COMMENT '已保存搜索页数',
  `primary_count` INT NOT NULL DEFAULT 0 COMMENT '主推荐数',
  `stop_reason` TEXT NULL COMMENT '停止搜索的证据或失败原因',
  `rule_version` VARCHAR(64) NULL COMMENT '本次候选门禁规则版本',
  `rule_config_json` TEXT NULL COMMENT '运行时规则、当前时间和阈值快照 JSON',
  `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
    ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_video_discovery_run_id` (`run_id`),
  UNIQUE KEY `uk_video_discovery_run_biz_grade` (`biz_dt`, `demand_grade_id`),
  KEY `idx_video_discovery_run_demand` (`demand_word`),
  KEY `idx_video_discovery_run_grade` (`demand_grade_id`),
  KEY `idx_video_discovery_run_biz_dt` (`biz_dt`),
  KEY `idx_video_discovery_run_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
  COMMENT='一次需求找视频运行';

CREATE TABLE IF NOT EXISTS `video_discovery_search` (
  `id` BIGINT NOT NULL AUTO_INCREMENT,
  `run_id` VARCHAR(64) NOT NULL COMMENT '发现运行 run_id',
  `search_key` VARCHAR(64) NOT NULL COMMENT '搜索参数哈希，仅用于追踪，不作为幂等键',
  `keyword` VARCHAR(256) NOT NULL COMMENT 'Agent 自主确定的搜索词',
  `query_reason` TEXT NOT NULL COMMENT '为何形成该搜索词、希望验证什么',
  `source_type` VARCHAR(32) NOT NULL
    COMMENT 'demand / seed / point / tag / author / pagination / mixed',
  `source_value` TEXT NULL COMMENT '来源点位、标签、作者或父关键词',
  `parent_search_id` BIGINT NULL COMMENT '由哪次搜索扩展而来',
  `provider` VARCHAR(32) NOT NULL DEFAULT 'internal_keyword'
    COMMENT 'internal_keyword / tikhub / internal_blogger',
  `provider_state_json` TEXT NULL
    COMMENT '供应方分页状态，如 TikHub search_id/backtrace',
  `content_type` VARCHAR(16) NOT NULL DEFAULT '视频' COMMENT '搜索内容类型',
  `sort_type` VARCHAR(32) NOT NULL DEFAULT '综合排序' COMMENT '搜索排序',
  `publish_time` VARCHAR(32) NOT NULL DEFAULT '不限' COMMENT '发布时间筛选',
  `cursor` VARCHAR(128) NOT NULL DEFAULT '0' COMMENT '本页游标',
  `page_no` INT NOT NULL DEFAULT 1 COMMENT '该关键词的页码',
  `results_count` INT NOT NULL DEFAULT 0 COMMENT '本页结果数',
  `new_candidate_count` INT NOT NULL DEFAULT 0 COMMENT '本页新增候选数',
  `has_more` TINYINT NOT NULL DEFAULT 0 COMMENT '接口是否有下一页',
  `next_cursor` VARCHAR(128) NULL COMMENT '下一页游标',
  `result_ids_json` TEXT NULL COMMENT '本页 aweme_id 列表 JSON',
  `status` VARCHAR(16) NOT NULL DEFAULT 'success' COMMENT 'success / failed',
  `error_message` TEXT NULL COMMENT '搜索失败信息',
  `raw_evidence_id` BIGINT NULL COMMENT '本页完整原始响应证据 id',
  `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
    ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  KEY `idx_video_discovery_search_run` (`run_id`, `id`),
  KEY `idx_video_discovery_search_parent` (`run_id`, `parent_search_id`),
  KEY `idx_video_discovery_search_keyword` (`keyword`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
  COMMENT='关键词、标签、作者或翻页搜索轨迹';

CREATE TABLE IF NOT EXISTS `video_discovery_candidate` (
  `id` BIGINT NOT NULL AUTO_INCREMENT,
  `run_id` VARCHAR(64) NOT NULL COMMENT '发现运行 run_id',
  `search_id` BIGINT NULL COMMENT '直接关联 video_discovery_search.id；历史数据允许为空',
  `aweme_id` VARCHAR(64) NOT NULL COMMENT '抖音视频 id',
  `title` VARCHAR(512) NULL COMMENT '视频标题',
  `content_link` VARCHAR(1024) NULL COMMENT '抖音页面链接',
  `author_name` VARCHAR(256) NULL COMMENT '作者名',
  `author_sec_uid` VARCHAR(256) NULL COMMENT '作者 sec_uid',
  `source_keywords_json` TEXT NULL COMMENT '命中过该视频的搜索词 JSON',
  `source_search_ids_json` TEXT NULL COMMENT '来源搜索轨迹 id JSON',
  `tags_json` TEXT NULL COMMENT '视频标签/话题 JSON',
  `publish_at` DATETIME NULL COMMENT '视频真实发布时间，按运行时区解释',
  `duration_seconds` DECIMAL(10,3) NULL COMMENT '视频时长（秒）',
  `play_count` BIGINT NULL COMMENT '播放数快照',
  `like_count` BIGINT NULL COMMENT '点赞数快照',
  `comment_count` BIGINT NULL COMMENT '评论数快照',
  `collect_count` BIGINT NULL COMMENT '收藏数快照',
  `share_count` BIGINT NULL COMMENT '分享数快照',
  `content_age_evidence_json` TEXT NULL COMMENT '视频点赞用户年龄证据 JSON',
  `account_age_evidence_json` TEXT NULL COMMENT '作者粉丝年龄证据 JSON',
  `age_normalization_json` TEXT NULL COMMENT '双侧年龄画像标准化结果 JSON',
  `content_50_plus_ratio` DECIMAL(8,6) NULL COMMENT '视频点赞用户中 50+ 占比',
  `content_50_plus_tgi` DECIMAL(10,4) NULL COMMENT '视频点赞用户 50+ TGI',
  `content_portrait_status` VARCHAR(16) NULL COMMENT '视频画像结论 pass / fail / missing',
  `account_50_plus_ratio` DECIMAL(8,6) NULL COMMENT '账号粉丝中 50+ 占比',
  `account_50_plus_tgi` DECIMAL(10,4) NULL COMMENT '账号粉丝 50+ TGI',
  `account_portrait_status` VARCHAR(16) NULL COMMENT '账号画像结论 pass / fail / missing',
  `portrait_conflict` TINYINT NOT NULL DEFAULT 0 COMMENT '视频与账号画像结论是否冲突',
  `temporal_type` VARCHAR(24) NULL COMMENT '时间内容类型',
  `temporal_status` VARCHAR(16) NULL COMMENT '时间有效性 pass / fail / unknown',
  `temporal_evidence_json` TEXT NULL COMMENT '时间语义、有效窗口和判断理由 JSON',
  `gate_status` VARCHAR(16) NULL COMMENT '硬门槛 pass / fail / pending',
  `gate_results_json` TEXT NULL COMMENT '逐项硬门槛结果 JSON',
  `reject_reason_code` VARCHAR(64) NULL COMMENT '主要淘汰原因码',
  `rule_version` VARCHAR(64) NULL COMMENT '候选评估使用的规则版本',
  `latest_search_evidence_id` BIGINT NULL COMMENT '最新搜索原始证据 id',
  `latest_detail_evidence_id` BIGINT NULL COMMENT '最新详情原始证据 id',
  `latest_content_portrait_evidence_id` BIGINT NULL COMMENT '最新内容画像原始证据 id',
  `latest_account_portrait_evidence_id` BIGINT NULL COMMENT '最新账号画像原始证据 id',
  `detail_fetch_status` VARCHAR(16) NULL COMMENT '详情获取状态',
  `content_portrait_fetch_status` VARCHAR(16) NULL COMMENT '内容画像获取状态',
  `account_portrait_fetch_status` VARCHAR(16) NULL COMMENT '账号画像获取状态',
  `evidence_version` INT NOT NULL DEFAULT 0 COMMENT '门禁输入数据版本',
  `gate_evidence_version` INT NULL COMMENT '最近门禁使用的证据版本',
  `latest_gate_evaluation_id` BIGINT NULL COMMENT '最近门禁评估记录 id',
  `gate_evaluated_at` DATETIME NULL COMMENT '最近门禁评估时间',
  `relevance_score` DECIMAL(8,6) NULL COMMENT 'R，范围 0~1',
  `elder_score` DECIMAL(8,6) NULL COMMENT 'E，范围 0~1',
  `share_score` DECIMAL(8,6) NULL COMMENT 'S，范围 0~1',
  `value_score` DECIMAL(8,2) NULL COMMENT '联合价值 V，范围 0~1',
  `decision_reason` TEXT NULL COMMENT '最终分池依据',
  `decision_bucket` VARCHAR(24) NOT NULL DEFAULT 'pending_evaluation'
    COMMENT '最终为 primary / rejected；pending_evaluation 仅为过程状态',
  `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
    ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  KEY `idx_video_discovery_candidate_search` (`search_id`, `id`),
  KEY `idx_video_discovery_candidate_bucket` (`run_id`, `decision_bucket`),
  KEY `idx_video_discovery_candidate_author` (`author_sec_uid`),
  CONSTRAINT `fk_video_discovery_candidate_search`
    FOREIGN KEY (`search_id`) REFERENCES `video_discovery_search` (`id`)
    ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
  COMMENT='本次运行发现的视频及评估快照';

CREATE TABLE IF NOT EXISTS `video_discovery_evidence` (
  `id` BIGINT NOT NULL AUTO_INCREMENT,
  `run_id` VARCHAR(64) NOT NULL,
  `search_id` BIGINT NULL,
  `trigger_candidate_id` BIGINT NULL,
  `aweme_id` VARCHAR(64) NULL,
  `author_sec_uid` VARCHAR(256) NULL,
  `subject_key` VARCHAR(320) NOT NULL,
  `evidence_type` VARCHAR(32) NOT NULL,
  `provider` VARCHAR(32) NOT NULL,
  `tool_call_id` VARCHAR(64) NOT NULL,
  `request_json` LONGTEXT NULL,
  `raw_response_json` LONGTEXT NULL,
  `normalized_json` LONGTEXT NULL,
  `response_sha256` VARCHAR(64) NULL,
  `fetch_status` VARCHAR(16) NOT NULL,
  `processing_status` VARCHAR(16) NOT NULL DEFAULT 'pending',
  `error_code` VARCHAR(64) NULL,
  `error_message` TEXT NULL,
  `schema_version` VARCHAR(32) NOT NULL DEFAULT 'find-agent-evidence-v1',
  `fetched_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `latency_ms` INT NULL,
  `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_video_discovery_evidence_call_subject`
    (`tool_call_id`, `evidence_type`, `subject_key`),
  KEY `idx_video_discovery_evidence_run_type` (`run_id`, `evidence_type`, `id`),
  KEY `idx_video_discovery_evidence_subject`
    (`run_id`, `aweme_id`, `evidence_type`, `id`),
  KEY `idx_video_discovery_evidence_processing` (`processing_status`, `id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
  COMMENT='find_agent 工具原始响应和规范化证据';

CREATE TABLE IF NOT EXISTS `video_discovery_gate_evaluation` (
  `id` BIGINT NOT NULL AUTO_INCREMENT,
  `run_id` VARCHAR(64) NOT NULL,
  `candidate_id` BIGINT NOT NULL,
  `rule_version` VARCHAR(64) NOT NULL,
  `evidence_version` INT NOT NULL,
  `gate_input_hash` VARCHAR(64) NOT NULL,
  `gate_input_json` LONGTEXT NOT NULL,
  `gate_result_json` LONGTEXT NOT NULL,
  `gate_status` VARCHAR(16) NOT NULL,
  `failed_reason_codes_json` TEXT NULL,
  `evaluated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_video_discovery_gate_input`
    (`candidate_id`, `rule_version`, `evidence_version`, `gate_input_hash`),
  KEY `idx_video_discovery_gate_candidate` (`candidate_id`, `id`),
  KEY `idx_video_discovery_gate_run_status` (`run_id`, `gate_status`, `id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
  COMMENT='find_agent 候选门禁评估历史';
