-- ============================================================
-- KTV服务 uapi/uapiio 补全迁移 Part 1
-- 输入字段使用 _file 命名规范（与 Sage image/video/audio 统一）
-- ============================================================

-- ASR语音识别
INSERT INTO uapiio (id, name, description, input_fields) VALUES (
  'ktv_asr_transcribe_io', 'KTV语音识别', '上传音频文件，返回识别文本和时间戳',
  '{"audio_file":{"type":"string","required":true,"description":"音频文件URL"},"language":{"type":"string","required":false,"default":"zh","description":"语言代码"}}'
) ON DUPLICATE KEY UPDATE description=VALUES(description), input_fields=VALUES(input_fields);

-- Demucs音频分离
INSERT INTO uapiio (id, name, description, input_fields) VALUES (
  'ktv_demucs_separate_io', 'KTV音频分离', '分离人声和伴奏',
  '{"audio_file":{"type":"string","required":true,"description":"音频文件URL"}}'
) ON DUPLICATE KEY UPDATE description=VALUES(description), input_fields=VALUES(input_fields);

-- 人脸检测
INSERT INTO uapiio (id, name, description, input_fields) VALUES (
  'ktv_face_detect_io', 'KTV人脸检测', '检测图像中的人脸位置',
  '{"image_file":{"type":"string","required":true,"description":"图像URL"}}'
) ON DUPLICATE KEY UPDATE description=VALUES(description), input_fields=VALUES(input_fields);

-- 人脸识别
INSERT INTO uapiio (id, name, description, input_fields) VALUES (
  'ktv_face_recognize_io', 'KTV人脸识别', '识别人脸身份',
  '{"image_file":{"type":"string","required":true,"description":"图像URL"},"face_id":{"type":"string","required":false,"description":"人脸ID"}}'
) ON DUPLICATE KEY UPDATE description=VALUES(description), input_fields=VALUES(input_fields);

-- 人脸比对
INSERT INTO uapiio (id, name, description, input_fields) VALUES (
  'ktv_face_compare_io', 'KTV人脸比对', '比较两张人脸的相似度',
  '{"image_file1":{"type":"string","required":true,"description":"图像1 URL"},"image_file2":{"type":"string","required":true,"description":"图像2 URL"}}'
) ON DUPLICATE KEY UPDATE description=VALUES(description), input_fields=VALUES(input_fields);

-- 字幕渲染
INSERT INTO uapiio (id, name, description, input_fields) VALUES (
  'ktv_subtitle_render_io', 'KTV字幕渲染', '将歌词时间轴渲染为ASS字幕文件',
  '{"lyrics_json":{"type":"string","required":true,"description":"歌词时间轴JSON"},"width":{"type":"integer","required":false,"default":1920,"description":"视频宽度"},"height":{"type":"integer","required":false,"default":1080,"description":"视频高度"}}'
) ON DUPLICATE KEY UPDATE description=VALUES(description), input_fields=VALUES(input_fields);

-- 视频合并
INSERT INTO uapiio (id, name, description, input_fields) VALUES (
  'ktv_merge_video_io', 'KTV视频合并', '合并视频、音频和字幕',
  '{"video_file":{"type":"string","required":false,"description":"视频URL"},"audio_file":{"type":"string","required":false,"description":"音频URL"},"subtitle_file":{"type":"string","required":false,"description":"ASS字幕URL"},"output_format":{"type":"string","required":false,"default":"mp4","description":"输出格式"}}'
) ON DUPLICATE KEY UPDATE description=VALUES(description), input_fields=VALUES(input_fields);

-- 歌曲评分
INSERT INTO uapiio (id, name, description, input_fields) VALUES (
  'ktv_songrate_evaluate_io', 'KTV歌曲评分', 'AI评估歌曲质量',
  '{"audio_file":{"type":"string","required":true,"description":"音频文件URL"},"scene":{"type":"string","required":false,"default":"pop","description":"场景类型"}}'
) ON DUPLICATE KEY UPDATE description=VALUES(description), input_fields=VALUES(input_fields);

-- 合成状态查询
INSERT INTO uapiio (id, name, description, input_fields) VALUES (
  'ktv_synth_status_io', 'KTV合成状态', '查询音乐合成任务状态',
  '{"task_id":{"type":"string","required":true,"description":"任务ID"}}'
) ON DUPLICATE KEY UPDATE description=VALUES(description), input_fields=VALUES(input_fields);

-- 超分辨率（异步）
INSERT INTO uapiio (id, name, description, input_fields) VALUES (
  'ktv_realesrgan_upscale_io', 'KTV超分辨率', '图像/视频超分辨率（异步任务）',
  '{"image_file":{"type":"string","required":true,"description":"图像URL"},"scale":{"type":"integer","required":false,"default":2,"description":"放大倍数"}}'
) ON DUPLICATE KEY UPDATE description=VALUES(description), input_fields=VALUES(input_fields);

-- 超分状态查询
INSERT INTO uapiio (id, name, description, input_fields) VALUES (
  'ktv_realesrgan_status_io', 'KTV超分状态', '查询超分任务状态',
  '{"task_id":{"type":"string","required":true,"description":"任务ID"}}'
) ON DUPLICATE KEY UPDATE description=VALUES(description), input_fields=VALUES(input_fields);

-- RVC声音转换
INSERT INTO uapiio (id, name, description, input_fields) VALUES (
  'ktv_rvc_convert_io', 'KTV声音转换', '声音克隆/变声',
  '{"audio_file":{"type":"string","required":true,"description":"输入音频URL"},"voice_model":{"type":"string","required":true,"description":"目标声音模型名"}}'
) ON DUPLICATE KEY UPDATE description=VALUES(description), input_fields=VALUES(input_fields);

-- 视频评估
INSERT INTO uapiio (id, name, description, input_fields) VALUES (
  'ktv_video_eval_evaluate_io', 'KTV视频评估', '评估视频质量',
  '{"video_file":{"type":"string","required":true,"description":"视频URL"}}'
) ON DUPLICATE KEY UPDATE description=VALUES(description), input_fields=VALUES(input_fields);
-- ============================================================
-- KTV服务 uapi 补全 Part 2
-- data使用_file命名; response用{%if error%}容错透传GPU响应
-- async: synth-generate(5s轮询), realesrgan-upscale(3s轮询)
-- ============================================================

-- 1. ASR语音识别 (sync)
UPDATE uapi SET stream='sync',headers='{"Content-Type":"application/json"}',
  data='{"audio_file":"{{audio_file}}"{%if language%},"language":"{{language}}"{%endif%}}',
  response='{%if error%}{"error":"{{error}}"}{%else%}{"status":"{{status}}","text":"{{text}}","segments":{{json.dumps(segments,ensure_ascii=False)}},"usage":{{json.dumps(usage,ensure_ascii=False)}}}{%endif%}',
  ioid='ktv_asr_transcribe_io' WHERE id='uapi_ktv_asr_transcribe';

-- 2. Demucs音频分离 (async)
UPDATE uapi SET stream='async',headers='{"Content-Type":"application/json"}',
  data='{"audio_path":"{{audio_file}}"{%if task_type%},"task_type":"{{task_type}}"{%endif%}}',
  response='{"taskid":"{{task_id}}","taskstatus":"PENDING","status":"PENDING"}',
  ioid='ktv_demucs_separate_io' WHERE id='uapi_ktv_demucs_separate';

-- 3. 人脸检测 (sync)
UPDATE uapi SET stream='sync',headers='{"Content-Type":"application/json"}',
  data='{"image_file":"{{image_file}}"}',
  response='{%if error%}{"error":"{{error}}"}{%else%}{"status":"{{status}}","faces":{{json.dumps(faces,ensure_ascii=False)}},"usage":{{json.dumps(usage,ensure_ascii=False)}}}{%endif%}',
  ioid='ktv_face_detect_io' WHERE id='uapi_ktv_face_detect';

-- 4. 人脸识别 (sync)
UPDATE uapi SET stream='sync',headers='{"Content-Type":"application/json"}',
  data='{"image_file":"{{image_file}}"{%if face_id%},"face_id":"{{face_id}}"{%endif%}}',
  response='{%if error%}{"error":"{{error}}"}{%else%}{"status":"{{status}}","matches":{{json.dumps(matches,ensure_ascii=False)}},"usage":{{json.dumps(usage,ensure_ascii=False)}}}{%endif%}',
  ioid='ktv_face_recognize_io' WHERE id='uapi_ktv_face_recognize';

-- 5. 人脸比对 (sync)
UPDATE uapi SET stream='sync',headers='{"Content-Type":"application/json"}',
  data='{"image_file1":"{{image_file1}}","image_file2":"{{image_file2}}"}',
  response='{%if error%}{"error":"{{error}}"}{%else%}{"status":"{{status}}","similarity":{{similarity}},"usage":{{json.dumps(usage,ensure_ascii=False)}}}{%endif%}',
  ioid='ktv_face_compare_io' WHERE id='uapi_ktv_face_compare';

-- 6. 字幕渲染 (sync)
UPDATE uapi SET stream='sync',headers='{"Content-Type":"application/json"}',
  data='{"lyrics_json":{{lyrics_json}}{%if width%},"width":{{width}}{%endif%}{%if height%},"height":{{height}}{%endif%}}',
  response='{%if error%}{"error":"{{error}}"}{%else%}{"status":"{{status}}","ass_url":"{{ass_url}}","usage":{{json.dumps(usage,ensure_ascii=False)}}}{%endif%}',
  ioid='ktv_subtitle_render_io' WHERE id='uapi_ktv_subtitle_render';

-- 7. 视频合并 (sync)
UPDATE uapi SET stream='sync',headers='{"Content-Type":"application/json"}',
  data='{%set c=joiner(",")%}{{%if video_file%}{{c()}}"video_file":"{{video_file}}"{%endif%}{%if audio_file%}{{c()}}"audio_file":"{{audio_file}}"{%endif%}{%if subtitle_file%}{{c()}}"subtitle_file":"{{subtitle_file}}"{%endif%}{%if output_format%}{{c()}}"output_format":"{{output_format}}"{%endif%}}',
  response='{%if error%}{"error":"{{error}}"}{%else%}{"status":"{{status}}","output_url":"{{output_url}}","duration":{{duration}},"usage":{{json.dumps(usage,ensure_ascii=False)}}}{%endif%}',
  ioid='ktv_merge_video_io' WHERE id='uapi_ktv_merge_video';

-- 8. 歌曲评分 (sync)
UPDATE uapi SET stream='sync',headers='{"Content-Type":"application/json"}',
  data='{"audio_file":"{{audio_file}}"{%if scene%},"scene":"{{scene}}"{%endif%}}',
  response='{%if error%}{"error":"{{error}}"}{%else%}{"status":"{{status}}","score":{{score}},"details":{{json.dumps(details,ensure_ascii=False)}},"usage":{{json.dumps(usage,ensure_ascii=False)}}}{%endif%}',
  ioid='ktv_songrate_evaluate_io' WHERE id='uapi_ktv_songrate_evaluate';

-- 9. 合成状态查询 (sync)
UPDATE uapi SET stream='sync',headers='{"Content-Type":"application/json"}',
  data='{"task_id":"{{task_id}}"}',
  response='{%if error%}{"error":"{{error}}"}{%elif status=="SUCCEEDED"%}{"taskstatus":"SUCCEEDED","output_url":"{{output_url}}","usage":{{json.dumps(usage,ensure_ascii=False)}}}{%elif status=="FAILED"%}{"taskstatus":"FAILED","error":"{{error}}"}{%else%}{"taskstatus":"PENDING"}{%endif%}',
  ioid='ktv_synth_status_io' WHERE id='uapi_ktv_synth_status';

-- 11. 超分辨率 (async提交)
UPDATE uapi SET stream='async',headers='{"Content-Type":"application/json"}',
  data='{"image_file":"{{image_file}}"{%if scale%},"scale":{{scale}}{%endif%}}',
  response='{"taskid":"{{task_id}}","taskstatus":"PENDING"}',
  ioid='ktv_realesrgan_upscale_io' WHERE id='uapi_ktv_realesrgan_upscale';

-- 12. 超分状态查询 (sync)
UPDATE uapi SET stream='sync',headers='{"Content-Type":"application/json"}',
  data='{"task_id":"{{task_id}}"}',
  response='{%if error%}{"error":"{{error}}"}{%elif status=="SUCCEEDED"%}{"taskstatus":"SUCCEEDED","output_url":"{{output_url}}","usage":{{json.dumps(usage,ensure_ascii=False)}}}{%elif status=="FAILED"%}{"taskstatus":"FAILED","error":"{{error}}"}{%else%}{"taskstatus":"PENDING"}{%endif%}',
  ioid='ktv_realesrgan_status_io' WHERE id='uapi_ktv_realesrgan_status';

-- 13. RVC声音转换 (sync)
UPDATE uapi SET stream='sync',headers='{"Content-Type":"application/json"}',
  data='{"audio_file":"{{audio_file}}","voice_model":"{{voice_model}}"}',
  response='{%if error%}{"error":"{{error}}"}{%else%}{"status":"{{status}}","output_url":"{{output_url}}","usage":{{json.dumps(usage,ensure_ascii=False)}}}{%endif%}',
  ioid='ktv_rvc_convert_io' WHERE id='uapi_ktv_rvc_convert';

-- 14. 视频评估 (sync)
UPDATE uapi SET stream='sync',headers='{"Content-Type":"application/json"}',
  data='{"video_file":"{{video_file}}"}',
  response='{%if error%}{"error":"{{error}}"}{%else%}{"status":"{{status}}","score":{{score}},"details":{{json.dumps(details,ensure_ascii=False)}},"usage":{{json.dumps(usage,ensure_ascii=False)}}}{%endif%}',
  ioid='ktv_video_eval_evaluate_io' WHERE id='uapi_ktv_video_eval_evaluate';

-- async query_apiname
UPDATE llm_api_map SET query_apiname='realesrgan-status',query_period=3 WHERE llmid='llm_ktv_realesrgan_upscale';

-- ppid (v1/models 过滤要求 ppid IS NOT NULL)
UPDATE llm_api_map SET ppid='pp_ktv' WHERE llmid LIKE 'llm_ktv%' AND ppid IS NULL;

-- upappkey (API调用鉴权必需)
INSERT INTO upappkey (id,upappid,ownerid,apikey,orgid)
SELECT 'ktv_gateway_key','ktv-gateway','UiEi7hKqAmU1-jqQEVhZe','','0'
WHERE NOT EXISTS (SELECT 1 FROM upappkey WHERE upappid='ktv-gateway');
-- ============================================================
-- KTV Pipeline v1 API RBAC 权限配置
-- 新增 /v1/pipeline/submit 端点权限
-- ============================================================

-- 权限路径（供 load_path.py 或不直接支持的模块参考）
-- 目录级
-- /llmage/v1/pipeline logined
-- /llmage/v1/pipeline/submit logined
-- 文件级
-- /llmage/v1/pipeline/submit/index.dspy logined

-- ============================================================
-- Customer 角色权限（API调用者需要）
-- ============================================================
INSERT INTO permission (id, path, name)
SELECT REPLACE(UUID(), '-', ''), '/llmage/v1/pipeline/submit/index.dspy', 'KTV流水线提交'
WHERE NOT EXISTS (
    SELECT 1 FROM permission WHERE path = '/llmage/v1/pipeline/submit/index.dspy'
);

-- 为 customer.admin 和 customer.user 角色授予权限
-- 注意：以下语句依赖 set_role_perm.py 或等效的角色-权限关联表
-- 如果用的是直接 role_permission 表：
INSERT IGNORE INTO role_permission (role_id, permission_id)
SELECT r.id, p.id
FROM role r, permission p
WHERE r.name IN ('customer.admin', 'customer.user')
AND p.path = '/llmage/v1/pipeline/submit/index.dspy';

-- ============================================================
-- 管理角色权限
-- ============================================================
INSERT IGNORE INTO role_permission (role_id, permission_id)
SELECT r.id, p.id
FROM role r, permission p
WHERE r.name IN ('owner.superuser', 'owner.admin', 'reseller.admin', 'reseller.operator')
AND p.path = '/llmage/v1/pipeline/submit/index.dspy';
-- ============================================================
-- KTV服务 定价修复 Part 4
-- 每个模型独立ppid + 按量计费(price_factors=字段名)
-- ============================================================

-- 1. 创建独立ppid（每模型一个）
INSERT INTO pricing_program (id,providerid,name) VALUES 
('pp_ktv_asr','FZoJv7EUEdKL3pUt0BQ5S','KTV-语音识别'),
('pp_ktv_demucs','FZoJv7EUEdKL3pUt0BQ5S','KTV-音频分离'),
('pp_ktv_face_detect','FZoJv7EUEdKL3pUt0BQ5S','KTV-人脸检测'),
('pp_ktv_face_recognize','FZoJv7EUEdKL3pUt0BQ5S','KTV-人脸识别'),
('pp_ktv_face_compare','FZoJv7EUEdKL3pUt0BQ5S','KTV-人脸比对'),
('pp_ktv_subtitle','FZoJv7EUEdKL3pUt0BQ5S','KTV-字幕渲染'),
('pp_ktv_merge','FZoJv7EUEdKL3pUt0BQ5S','KTV-视频合并'),
('pp_ktv_songrate','FZoJv7EUEdKL3pUt0BQ5S','KTV-歌曲评分'),

('pp_ktv_synth_status','FZoJv7EUEdKL3pUt0BQ5S','KTV-合成状态'),
('pp_ktv_realesrgan','FZoJv7EUEdKL3pUt0BQ5S','KTV-超分辨率'),
('pp_ktv_realesrgan_status','FZoJv7EUEdKL3pUt0BQ5S','KTV-超分状态'),
('pp_ktv_rvc','FZoJv7EUEdKL3pUt0BQ5S','KTV-声音转换'),
('pp_ktv_video_eval','FZoJv7EUEdKL3pUt0BQ5S','KTV-视频评估')
ON DUPLICATE KEY UPDATE providerid=VALUES(providerid);

-- 2. 迁移 pricing_program_timing 到新 ppid
UPDATE pricing_program_timing SET ppid='pp_ktv_asr' WHERE id='pt_ktv_asr_transcribe';
UPDATE pricing_program_timing SET ppid='pp_ktv_demucs' WHERE id='pt_ktv_demucs_separate';
UPDATE pricing_program_timing SET ppid='pp_ktv_face_detect' WHERE id='pt_ktv_face_detect';
UPDATE pricing_program_timing SET ppid='pp_ktv_face_recognize' WHERE id='pt_ktv_face_recognize';
UPDATE pricing_program_timing SET ppid='pp_ktv_face_compare' WHERE id='pt_ktv_face_compare';
UPDATE pricing_program_timing SET ppid='pp_ktv_subtitle' WHERE id='pt_ktv_subtitle_render';
UPDATE pricing_program_timing SET ppid='pp_ktv_merge' WHERE id='pt_ktv_merge_video';
UPDATE pricing_program_timing SET ppid='pp_ktv_songrate' WHERE id='pt_ktv_songrate_evaluate';

UPDATE pricing_program_timing SET ppid='pp_ktv_synth_status' WHERE id='pt_ktv_synth_status';
UPDATE pricing_program_timing SET ppid='pp_ktv_realesrgan' WHERE id='pt_ktv_realesrgan_upscale';
UPDATE pricing_program_timing SET ppid='pp_ktv_realesrgan_status' WHERE id='pt_ktv_realesrgan_status';
UPDATE pricing_program_timing SET ppid='pp_ktv_rvc' WHERE id='pt_ktv_rvc_convert';
UPDATE pricing_program_timing SET ppid='pp_ktv_video_eval' WHERE id='pt_ktv_video_eval_evaluate';

-- 3. 更新 pricing_data YAML：price_factors=字段名（按量计费）
-- asr: audio_seconds × 0.01
UPDATE pricing_program_timing SET pricing_data='unit_values:\n  audio_seconds: 1\nfields:\n  price_factors:\n    type: string\n    role: factor\n    label: 计价因子\n  unit_prices:\n    type: float\n    role: factor\n    label: 单位定价\n  unit:\n    type: string\n    role: factor\n    label: 计价单位\npricings:\n- price_factors: audio_seconds\n  unit_prices: 0.01\n  unit: audio_seconds' WHERE id='pt_ktv_asr_transcribe';

-- demucs: audio_seconds × 0.02
UPDATE pricing_program_timing SET pricing_data='unit_values:\n  audio_seconds: 1\nfields:\n  price_factors:\n    type: string\n    role: factor\n    label: 计价因子\n  unit_prices:\n    type: float\n    role: factor\n    label: 单位定价\n  unit:\n    type: string\n    role: factor\n    label: 计价单位\npricings:\n- price_factors: audio_seconds\n  unit_prices: 0.02\n  unit: audio_seconds' WHERE id='pt_ktv_demucs_separate';

-- face-detect: detect_count × 0.10
UPDATE pricing_program_timing SET pricing_data='unit_values:\n  detect_count: 1\nfields:\n  price_factors:\n    type: string\n    role: factor\n    label: 计价因子\n  unit_prices:\n    type: float\n    role: factor\n    label: 单位定价\n  unit:\n    type: string\n    role: factor\n    label: 计价单位\npricings:\n- price_factors: detect_count\n  unit_prices: 0.10\n  unit: detect_count' WHERE id='pt_ktv_face_detect';

-- face-recognize: recognize_count × 0.10
UPDATE pricing_program_timing SET pricing_data='unit_values:\n  recognize_count: 1\nfields:\n  price_factors:\n    type: string\n    role: factor\n    label: 计价因子\n  unit_prices:\n    type: float\n    role: factor\n    label: 单位定价\n  unit:\n    type: string\n    role: factor\n    label: 计价单位\npricings:\n- price_factors: recognize_count\n  unit_prices: 0.10\n  unit: recognize_count' WHERE id='pt_ktv_face_recognize';

-- face-compare: compare_count × 0.10
UPDATE pricing_program_timing SET pricing_data='unit_values:\n  compare_count: 1\nfields:\n  price_factors:\n    type: string\n    role: factor\n    label: 计价因子\n  unit_prices:\n    type: float\n    role: factor\n    label: 单位定价\n  unit:\n    type: string\n    role: factor\n    label: 计价单位\npricings:\n- price_factors: compare_count\n  unit_prices: 0.10\n  unit: compare_count' WHERE id='pt_ktv_face_compare';

-- subtitle: subtitle_count × 0.01
UPDATE pricing_program_timing SET pricing_data='unit_values:\n  subtitle_count: 1\nfields:\n  price_factors:\n    type: string\n    role: factor\n    label: 计价因子\n  unit_prices:\n    type: float\n    role: factor\n    label: 单位定价\n  unit:\n    type: string\n    role: factor\n    label: 计价单位\npricings:\n- price_factors: subtitle_count\n  unit_prices: 0.01\n  unit: subtitle_count' WHERE id='pt_ktv_subtitle_render';

-- merge: output_seconds × 0.01
UPDATE pricing_program_timing SET pricing_data='unit_values:\n  output_seconds: 1\nfields:\n  price_factors:\n    type: string\n    role: factor\n    label: 计价因子\n  unit_prices:\n    type: float\n    role: factor\n    label: 单位定价\n  unit:\n    type: string\n    role: factor\n    label: 计价单位\npricings:\n- price_factors: output_seconds\n  unit_prices: 0.01\n  unit: output_seconds' WHERE id='pt_ktv_merge_video';

-- songrate: audio_seconds × 0.005
UPDATE pricing_program_timing SET pricing_data='unit_values:\n  audio_seconds: 1\nfields:\n  price_factors:\n    type: string\n    role: factor\n    label: 计价因子\n  unit_prices:\n    type: float\n    role: factor\n    label: 单位定价\n  unit:\n    type: string\n    role: factor\n    label: 计价单位\npricings:\n- price_factors: audio_seconds\n  unit_prices: 0.005\n  unit: audio_seconds' WHERE id='pt_ktv_songrate_evaluate';

-- synth-generate: audio_seconds × 0.20
UPDATE pricing_program_timing SET pricing_data='unit_values:\n  audio_seconds: 1\nfields:\n  price_factors:\n    type: string\n    role: factor\n    label: 计价因子\n  unit_prices:\n    type: float\n    role: factor\n    label: 单位定价\n  unit:\n    type: string\n    role: factor\n    label: 计价单位\npricings:\n- price_factors: audio_seconds\n  unit_prices: 0.20\n  unit: audio_seconds' WHERE id='pt_ktv_synth_generate';

-- synth-status: flat 0.01
UPDATE pricing_program_timing SET pricing_data='unit_values:\n  次: 1\nfields:\n  price_factors:\n    type: string\n    role: factor\n    label: 计价因子\n  unit_prices:\n    type: float\n    role: factor\n    label: 单位定价\n  unit:\n    type: string\n    role: factor\n    label: 计价单位\npricings:\n- price_factors: flat\n  unit_prices: 0.01\n  unit: 次' WHERE id='pt_ktv_synth_status';

-- realesrgan-upscale: image_count × 0.50
UPDATE pricing_program_timing SET pricing_data='unit_values:\n  image_count: 1\nfields:\n  price_factors:\n    type: string\n    role: factor\n    label: 计价因子\n  unit_prices:\n    type: float\n    role: factor\n    label: 单位定价\n  unit:\n    type: string\n    role: factor\n    label: 计价单位\npricings:\n- price_factors: image_count\n  unit_prices: 0.50\n  unit: image_count' WHERE id='pt_ktv_realesrgan_upscale';

-- realesrgan-status: flat 0.01
UPDATE pricing_program_timing SET pricing_data='unit_values:\n  次: 1\nfields:\n  price_factors:\n    type: string\n    role: factor\n    label: 计价因子\n  unit_prices:\n    type: float\n    role: factor\n    label: 单位定价\n  unit:\n    type: string\n    role: factor\n    label: 计价单位\npricings:\n- price_factors: flat\n  unit_prices: 0.01\n  unit: 次' WHERE id='pt_ktv_realesrgan_status';

-- rvc: audio_seconds × 0.15
UPDATE pricing_program_timing SET pricing_data='unit_values:\n  audio_seconds: 1\nfields:\n  price_factors:\n    type: string\n    role: factor\n    label: 计价因子\n  unit_prices:\n    type: float\n    role: factor\n    label: 单位定价\n  unit:\n    type: string\n    role: factor\n    label: 计价单位\npricings:\n- price_factors: audio_seconds\n  unit_prices: 0.15\n  unit: audio_seconds' WHERE id='pt_ktv_rvc_convert';

-- video-eval: video_seconds × 0.05
UPDATE pricing_program_timing SET pricing_data='unit_values:\n  video_seconds: 1\nfields:\n  price_factors:\n    type: string\n    role: factor\n    label: 计价因子\n  unit_prices:\n    type: float\n    role: factor\n    label: 单位定价\n  unit:\n    type: string\n    role: factor\n    label: 计价单位\npricings:\n- price_factors: video_seconds\n  unit_prices: 0.05\n  unit: video_seconds' WHERE id='pt_ktv_video_eval_evaluate';

-- 4. 更新 llm_api_map 指向独立 ppid
UPDATE llm_api_map SET ppid='pp_ktv_asr' WHERE llmid='llm_ktv_asr_transcribe';
UPDATE llm_api_map SET ppid='pp_ktv_demucs' WHERE llmid='llm_ktv_demucs_separate';
UPDATE llm_api_map SET ppid='pp_ktv_face_detect' WHERE llmid='llm_ktv_face_detect';
UPDATE llm_api_map SET ppid='pp_ktv_face_recognize' WHERE llmid='llm_ktv_face_recognize';
UPDATE llm_api_map SET ppid='pp_ktv_face_compare' WHERE llmid='llm_ktv_face_compare';
UPDATE llm_api_map SET ppid='pp_ktv_subtitle' WHERE llmid='llm_ktv_subtitle_render';
UPDATE llm_api_map SET ppid='pp_ktv_merge' WHERE llmid='llm_ktv_merge_video';
UPDATE llm_api_map SET ppid='pp_ktv_songrate' WHERE llmid='llm_ktv_songrate_evaluate';

UPDATE llm_api_map SET ppid='pp_ktv_synth_status' WHERE llmid='llm_ktv_synth_status';
UPDATE llm_api_map SET ppid='pp_ktv_realesrgan' WHERE llmid='llm_ktv_realesrgan_upscale';
UPDATE llm_api_map SET ppid='pp_ktv_realesrgan_status' WHERE llmid='llm_ktv_realesrgan_status';
UPDATE llm_api_map SET ppid='pp_ktv_rvc' WHERE llmid='llm_ktv_rvc_convert';
UPDATE llm_api_map SET ppid='pp_ktv_video_eval' WHERE llmid='llm_ktv_video_eval_evaluate';
-- ============================================================
-- KTV服务 数据模板修复 Part 5
-- 匹配GPU实际参数名 + demucs async改造
-- ============================================================

-- asr: audio_file → audio_path
UPDATE uapi SET data='{"audio_path":"{{audio_file}}"{%if language%},"language":"{{language}}"{%endif%}}' WHERE id='uapi_ktv_asr_transcribe';

-- demucs: audio_file → audio_path  
UPDATE uapi SET data='{"audio_path":"{{audio_file}}"{%if task_type%},"task_type":"{{task_type}}"{%endif%}}' WHERE id='uapi_ktv_demucs_separate';

-- face-detect: image_file → images list
UPDATE uapi SET data='{"images":["{{image_file}}"]}' WHERE id='uapi_ktv_face_detect';

-- face-recognize: image_file → images list
UPDATE uapi SET data='{"images":["{{image_file}}"]{%if face_id%},"face_id":"{{face_id}}"{%endif%}}' WHERE id='uapi_ktv_face_recognize';

-- face-compare: image_file1→embedding1, image_file2→embedding2
UPDATE uapi SET data='{"embedding1":"{{image_file1}}","embedding2":"{{image_file2}}"}' WHERE id='uapi_ktv_face_compare';

-- subtitle: lyrics_json → lyrics
UPDATE uapi SET data='{"lyrics":{{lyrics_json}}{%if width%},"width":{{width}}{%endif%}{%if height%},"height":{{height}}{%endif%}}' WHERE id='uapi_ktv_subtitle_render';

-- merge: video_file→video_url, audio_file→audio_path
UPDATE uapi SET data='{%set c=joiner(",")%}{{%if video_file%}{{c()}}"video_url":"{{video_file}}"{%endif%}{%if audio_file%}{{c()}}"audio_path":"{{audio_file}}"{%endif%}{%if subtitle_file%}{{c()}}"subtitle_url":"{{subtitle_file}}"{%endif%}{%if output_format%}{{c()}}"output_format":"{{output_format}}"{%endif%}}' WHERE id='uapi_ktv_merge_video';

-- songrate: audio_file→audio_path
UPDATE uapi SET data='{"audio_path":"{{audio_file}}"{%if scene%},"scene":"{{scene}}"{%endif%}}' WHERE id='uapi_ktv_songrate_evaluate';

-- synth-status: GET, params in query string, no body
UPDATE uapi SET httpmethod='GET', data=NULL, path='/synth/api/synth-status?task_id={{taskid}}' WHERE id='uapi_ktv_synth_status';

-- realesrgan-upscale: image_file→image_url
UPDATE uapi SET data='{"image_url":"{{image_file}}"{%if scale%},"scale":{{scale}}{%endif%}}' WHERE id='uapi_ktv_realesrgan_upscale';

-- realesrgan-status: GET, params in query string, no body
UPDATE uapi SET httpmethod='GET', data=NULL, path='/realesrgan/api/realesrgan-status?task_id={{taskid}}' WHERE id='uapi_ktv_realesrgan_status';

-- rvc: audio_file→audio_path, voice_model→model
UPDATE uapi SET data='{"audio_path":"{{audio_file}}","model":"{{voice_model}}"}' WHERE id='uapi_ktv_rvc_convert';

-- video-eval: video_file→video_url
UPDATE uapi SET data='{"video_url":"{{video_file}}"}' WHERE id='uapi_ktv_video_eval_evaluate';

-- ============================================================
-- demucs async 改造: status 查询端点 + query_apiname
-- ============================================================

INSERT INTO uapi (id,name,title,description,path,httpmethod,upappid,stream,headers,data,response,ioid) 
VALUES ('uapi_ktv_demucs_status','demucs-status','Demucs Status',
'Query demucs task','/demucs/api/demucs-status?task_id={{taskid}}','GET',
'ktv-gateway','sync','{"Content-Type":"application/json"}',NULL,
'{"status":"{{status}}","vocals_url":"{{vocals_url}}","accompaniment_url":"{{accompaniment_url}}","duration":{{duration}},"usage":{{json.dumps(usage,ensure_ascii=False)}}}',
'ktv_demucs_separate_io')
ON DUPLICATE KEY UPDATE response=VALUES(response);

UPDATE llm_api_map SET query_apiname='demucs-status',query_period=5 WHERE llmid='llm_ktv_demucs_separate';

-- ============================================================
-- 补充缺失的 pricing_program_timing 记录
-- ============================================================
INSERT INTO pricing_program_timing (id,ppid,name,pricing_data,enabled_date,expired_date) VALUES 
('pt_ktv_face_compare','pp_ktv_face_compare','KTV人脸比对','unit_values:\n  compare_count: 1\nfields:\n  price_factors:\n    type: string\n    role: factor\n    label: 计价因子\n  unit_prices:\n    type: float\n    role: factor\n    label: 单位定价\n  unit:\n    type: string\n    role: factor\n    label: 计价单位\npricings:\n- price_factors: compare_count\n  unit_prices: 0.10\n  unit: compare_count','2025-01-01','9999-12-31'),
('pt_ktv_synth_status','pp_ktv_synth_status','KTV合成状态','unit_values:\n  次: 1\nfields:\n  price_factors:\n    type: string\n    role: factor\n    label: 计价因子\n  unit_prices:\n    type: float\n    role: factor\n    label: 单位定价\n  unit:\n    type: string\n    role: factor\n    label: 计价单位\npricings:\n- price_factors: flat\n  unit_prices: 0.01\n  unit: 次','2025-01-01','9999-12-31'),
('pt_ktv_realesrgan_status','pp_ktv_realesrgan_status','KTV超分状态','unit_values:\n  次: 1\nfields:\n  price_factors:\n    type: string\n    role: factor\n    label: 计价因子\n  unit_prices:\n    type: float\n    role: factor\n    label: 单位定价\n  unit:\n    type: string\n    role: factor\n    label: 计价单位\npricings:\n- price_factors: flat\n  unit_prices: 0.01\n  unit: 次','2025-01-01','9999-12-31')
ON DUPLICATE KEY UPDATE ppid=VALUES(ppid), pricing_data=VALUES(pricing_data);
