#!/usr/bin/env ruby
# frozen_string_literal: true

# 百炼(DashScope) 语音 SDK 示例 CLI（Ruby 版）—— 8 项能力 + models 清单。
# API Key：--apikey sk-xxx 或环境变量 DASHSCOPE_API_KEY。

require_relative '../lib/dashscope'

# 真机验证清单（与 C#/PHP 交付 demo 同一批事实；★ = 该命令 --model 默认值）。
VERIFIED = [
  %w[asr qwen-audio-3.1-asr-flash-streaming 1 默认。持续下发中间结果],
  %w[asr qwen-audio-3.1-asr-flash-message 1 默认只出定稿；intermediate_result_enabled 才有中间结果],
  %w[asr qwen-audio-3.0-asr-flash-streaming 1 上一代，行为同 3.1 streaming],
  %w[asr fun-asr-realtime 1 Fun-ASR 线实时模型],
  ['asr', 'fun-asr-flash-8k-realtime', '1', '8kHz 电话音频：sample_rate 8000'],
  %w[asr paraformer-realtime-v2 1 老一代；会把「百炼」写成「百练」],
  ['asr', 'paraformer-realtime-8k-v2', '1', '8kHz：sample_rate 8000'],
  ['asr', 'fun-asr-realtime-2026-02-28', '1', 'fun-asr-realtime 的快照版'],
  ['asr', 'fun-asr-flash-8k-realtime-2026-01-28', '1', '8kHz 快照版'],
  ['asr', 'qwen-audio-3.0-asr-flash-message', '0', '服务端无此名；-message 只有 3.1 有'],
  ['tts', 'qwen-audio-3.1-tts-flash', '1', '默认。音色必须带 _v3.1；按 token 计费（usage_text）'],
  ['tts', 'qwen-audio-3.1-tts-plus', '1', '音色 longanlingxin_v3.1；按 token 计费'],
  ['tts', 'qwen-audio-3.0-tts-flash', '1', '音色不带后缀（longanfengyue）；按 token 计费'],
  ['tts', 'qwen-audio-3.0-tts-plus', '1', '音色 longanlingxin；按 token 计费'],
  ['tts', 'cosyvoice-v3-flash', '1', '音色 longanyang 或 longanhuan_v3'],
  ['tts', 'cosyvoice-v3-plus', '1', '音色 longanyang'],
  ['tts', 'cosyvoice-v2', '1', '音色 longxiaochun_v2'],
  ['tts', 'qwen-audio-3.1-tts-next', '1', 'Audiogen：text_prompt 经 extra_parameters_json 传入，慢，stop_timeout 要放大'],
  ['tts', 'cosyvoice-v3.5-flash', '0', '只吃复刻/设计音色 id，系统音色一律 [418]'],
  ['tts', 'cosyvoice-v3.5-plus', '0', '同上'],
  ['tts', 'qwen3-tts-flash', '0', 'ModelNotFound：不走这套 task 合成协议'],
  ['tts', 'qwen3-tts-flash-realtime', '0', 'Invalid message：报文形态不同'],
  ['sambert', 'sambert-zhichu-v1', '1', '默认。48kHz 舌尖男声，sample_rate 48000 为原生；按字符计费'],
  ['sambert', 'sambert-zhinan-v1', '1', '48kHz 广告男声'],
  ['sambert', 'sambert-zhijia-v1', '1', '48kHz 标准女声'],
  ['sambert', 'sambert-zhihao-v1', '1', '16kHz 咨询男声'],
  ['sambert', 'sambert-zhishu-v1', '1', '16kHz 资讯男声'],
  ['sambert', 'sambert-zhimiao-emo-v1', '1', '16kHz 多情感女声'],
  ['sambert', 'sambert-beth-v1', '1', '美式英文 咨询女声：待合成文本请用英文'],
  ['sambert', 'sambert-brian-v1', '1', '美式英文 客服男声：待合成文本请用英文'],
  ['sambert', 'sambert-xiaoyun-v1', '0', '平台在册清单没有这个名字：Model not exist'],
  ['filetrans', 'qwen-audio-3.1-asr-flash-filetrans', '1', '默认'],
  %w[filetrans qwen-audio-3.0-asr-flash-filetrans 1 上一代],
  ['filetrans', 'fun-asr', '1', '支持 diarization_enabled；只能走这一面'],
  %w[filetrans paraformer-v2 1 老一代，同一套参数],
  %w[filetrans paraformer-8k-v2 1 8kHz 电话录音],
  ['filetrans', 'qwen3-asr-flash-filetrans', '0', '报文形态不同（不读 input.file_urls）'],
  %w[flash qwen-audio-3.1-asr-flash 1 默认],
  %w[flash qwen-audio-3.0-asr-flash 1 上一代],
  ['flash', 'fun-asr-flash-2026-06-15', '1', '带日期快照，确实存在且可用'],
  ['flash', 'qwen3-asr-flash', '0', '平台在册但报文形态不同，别硬调'],
  ['chat', 'qwen-audio-3.1-realtime-plus', '1', '默认。对话音色与合成线不通用'],
  %w[chat qwen-audio-3.1-realtime-flash 1 同 3.1 plus，轻量档],
  %w[chat qwen-audio-3.0-realtime-plus 1 上一代],
  %w[chat qwen-audio-3.0-realtime-flash 1 上一代轻量档],
  ['chat', 'qwen3.5-omni-plus-realtime', '1', '不给音色即可；基名偶发不起本轮'],
  ['chat', 'qwen3.5-omni-plus-realtime-2026-03-15', '1', '3.5 plus 的快照'],
  %w[chat qwen3.5-omni-flash-realtime 1 轻量档],
  ['chat', 'qwen3.8-omni-flash-realtime', '1', '必须显式音色；示例工程不给 voice 时自动补 Tina'],
  ['chat', 'qwen3-omni-flash-realtime-2025-09-15', '1', '老快照：VAD 不起本轮，需 turn_detection_mode push_to_talk'],
  ['live', 'qwen-audio-3.1-live', '1', '默认。全双工方言：session.update 必带前台模型+delegation；按会话秒计费（最少 3 秒）'],
  ['live', 'qwen-audio-4.0-live', '0', 'URL 无此名：握手即被关，live 入口现仅 3.1'],
  ['live', 'qwen-audio-3.0-live', '0', '同上，服务端无此名'],
  ['live', 'qwen-audio-live', '0', '无裸名入口'],
  ['translate', 'qwen3.5-livetranslate-flash-realtime', '1', '默认。内部 ASR 可用 transcription_model 换'],
  ['translate', 'qwen3.5-livetranslate-flash-realtime-2026-05-19', '1', '3.5 的快照版'],
  ['translate', 'qwen3.8-livetranslate-flash-realtime', '1', '必须显式 voice（Serena/Ethan/Dylan/Ryan/longanqian）'],
  ['translate', 'qwen3-livetranslate-flash-realtime', '0', '2026-10-10 起下线：推流即被关']
].map { |f, m, ok, *rest| { face: f, model: m, works: ok == '1', note: rest.join(' ') } }

TTS_VOICES = {
  'qwen-audio-3.1-tts-flash' => 'longanfengyue_v3.1',
  'qwen-audio-3.1-tts-plus' => 'longanlingxin_v3.1',
  'qwen-audio-3.1-tts-next' => 'longanfengyue_v3.1',
  'qwen-audio-3.0-tts-flash' => 'longanfengyue',
  'qwen-audio-3.0-tts-plus' => 'longanlingxin',
  'cosyvoice-v3-flash' => 'longanhuan_v3',
  'cosyvoice-v3-plus' => 'longanyang',
  'cosyvoice-v2' => 'longxiaochun_v2'
}.freeze

def parse_opts(list)
  out = {}
  i = 0
  while i < list.length
    if list[i].to_s.start_with?('--')
      k = list[i][2..]
      if i + 1 < list.length && !list[i + 1].to_s.start_with?('--')
        out[k] = list[i + 1]
        i += 2
        next
      else
        out[k] = true
      end
    end
    i += 1
  end
  out
end

def need(o, k)
  v = o[k]
  abort("用法有误：缺少必填参数 --#{k}") if v.nil? || v == true

  v
end

def maybe(o, k, d = '')
  v = o.key?(k) ? o[k] : d
  v == true ? d : v.to_s
end

def tri(o, k)
  return nil unless o.key?(k)

  v = o[k]
  return true if v == true

  %w[1 true on yes].include?(v.to_s.downcase)
end

def default_model(face)
  VERIFIED.find { |r| r[:face] == face && r[:works] }[:model]
end

def tts_voice_for(model)
  return TTS_VOICES[model] if TTS_VOICES.key?(model)
  return 'longanhuan_v3' if model.start_with?('cosyvoice-v3')
  return 'longxiaochun_v2' if model.start_with?('cosyvoice')
  return DashScope::ModelRouting.qwen_audio_tts_model?(model) ?
           (model.start_with?('qwen-audio-3.1') ? 'longanfengyue_v3.1' : 'longanfengyue') : 'longxiaochun_v2'
end

cmd = ARGV[0]
o = parse_opts(ARGV[1..] || [])

begin
  case cmd
  when 'asr'
    audio = need(o, 'audio')
    asr = DashScope::Speech::FunAsrSpeechTranscriber.new(
      api_key: maybe(o, 'apikey', nil),
      model: maybe(o, 'model', default_model('asr')),
      format: maybe(o, 'format', 'pcm'),
      sample_rate: maybe(o, 'sample-rate', '16000').to_i,
      max_sentence_silence: maybe(o, 'max-sentence-silence', '0').to_i.then { |v| v.positive? ? v : nil },
      intermediate_result_enabled: tri(o, 'intermediate'),
      url: maybe(o, 'url', 'wss://dashscope.aliyuncs.com/api-ws/v1/inference'),
      stop_timeout: maybe(o, 'stop-timeout', '30').to_f
    )
    asr.on_sentence_begin = ->(s, _) { puts "[句首 ##{s.sentence_id}]" }
    asr.on_partial_result = ->(s, _) { print "\r[中间 ##{s.sentence_id} #{s.begin_time_ms}ms] #{s.text}          " }
    asr.on_sentence_end = ->(s, _) { puts "\n[定稿 ##{s.sentence_id} #{s.begin_time_ms}-#{s.end_time_ms}ms] #{s.text}" }
    asr.on_completed = ->(dur, _) { puts "识别完成。usage.duration=#{dur || '?'}s" }
    asr.transcribe_pcm_file(audio, 20, realtime: !o.key?('fast'))

  when 'tts'
    text = need(o, 'text')
    output = maybe(o, 'output', 'tts_out.bin')
    model = maybe(o, 'model', default_model('tts'))
    if DashScope::ModelRouting.sambert_model?(model)
      abort("Sambert 不走 tts 的流式方言：文本必须在 run-task 里一次交完。\n" \
            "请改用：ruby bin/dashscope sambert --text \"…\" --output out.wav --model #{model}")
    end
    opts = {
      api_key: maybe(o, 'apikey', nil),
      model: model,
      voice: maybe(o, 'voice', tts_voice_for(model)),
      format: maybe(o, 'format', 'pcm'),
      sample_rate: maybe(o, 'sample-rate', '22050').to_i,
      stop_timeout: maybe(o, 'stop-timeout', '30').to_f
    }
    prompt = maybe(o, 'text-prompt')
    prompt = text if prompt.empty? && model.end_with?('-tts-next')
    unless prompt.empty?
      opts[:extra_parameters_json] = JSON.generate(text_prompt: prompt)
      opts[:stop_timeout] = [opts[:stop_timeout], 180.0].max
    end
    tts = DashScope::Speech::CosyVoiceSpeechSynthesizer.new(**opts)
    tts.on_sentence = ->(e) { puts "[#{e.phase} ##{e.sentence_index}] #{e.original_text}#{e.billed_characters ? "（计费 #{e.billed_characters} 字符）" : ''}" }
    total = 0
    File.open(output, 'wb') do |f|
      tts.stream_audio(text.split('|').map(&:strip).reject(&:empty?)) do |chunk|
        f.write(chunk)
        total += chunk.bytesize
      end
    end
    puts "合成完毕：#{text.split('|').size} 段文本 → #{output}（#{total} 字节），model=#{model} voice=#{opts[:voice]}。"
    puts "计费：#{tts.usage_text}" if tts.usage_text

  when 'sambert'
    text = o.key?('text-file') && o['text-file'] != true ? File.read(o['text-file']) : need(o, 'text')
    output = maybe(o, 'output', 'sambert_out.wav')
    model = maybe(o, 'model', default_model('sambert'))
    tts = DashScope::Speech::SambertSpeechSynthesizer.new(
      api_key: maybe(o, 'apikey', nil),
      model: model,
      format: maybe(o, 'format', 'wav'),
      sample_rate: maybe(o, 'sample-rate', '16000').to_i,
      volume: maybe(o, 'volume', '-1').to_i.then { |v| v >= 0 ? v : nil },
      rate: maybe(o, 'rate', '-1').to_f.then { |v| v.positive? ? v : nil },
      pitch: maybe(o, 'pitch', '-1').to_f.then { |v| v.positive? ? v : nil },
      word_timestamp_enabled: tri(o, 'word-timestamp'),
      phoneme_timestamp_enabled: tri(o, 'phoneme-timestamp'),
      stop_timeout: maybe(o, 'stop-timeout', '120').to_f
    )
    tts.on_timestamps = lambda do |e|
      words = e.words || []
      phonemes = words.sum { |w| (w['phonemes'] || []).size }
      puts "[时间戳 #{e.begin_time_ms}-#{e.end_time_ms}ms] #{words.size} 字/#{phonemes} 音素" \
           "#{e.billed_characters ? "（计费 #{e.billed_characters} 字符）" : ''}"
    end
    total = 0
    File.open(output, 'wb') { |f| tts.synthesize(text) { |c| f.write(c); total += c.bytesize } }
    fmt = maybe(o, 'format', 'wav')
    if fmt == 'wav' && total >= 44
      head = File.binread(output, 44)
      hz = head[24, 4].unpack1('V')
      puts "WAV 文件头：#{hz} Hz / #{head[22, 2].unpack1('v')} 声道"
    end
    puts "合成完毕：#{text.length} 字文本 → #{output}（#{total} 字节），model=#{model}。"
    puts "计费：#{tts.usage_text}" if tts.usage_text
    puts '提示：Sambert 的文本在 run-task 里一次性全量上行，一段文本一个任务；仅支持华北2（北京）地域。'

  when 'filetrans'
    req = DashScope::Transcription::FileTranscriber::Request.new(
      model: maybe(o, 'model', default_model('filetrans')),
      file_urls: [need(o, 'file-url')],
      diarization_enabled: o.key?('diarization') ? true : nil
    )
    client = DashScope::Transcription::FileTranscriber.new(
      api_key: maybe(o, 'apikey', nil),
      url: maybe(o, 'url', 'https://dashscope.aliyuncs.com/api/v1/services/audio/asr/transcription'),
      poll_interval: maybe(o, 'poll-ms', '500').to_f / 1000,
      completion_timeout: maybe(o, 'timeout', '600').to_f
    )
    outputs = client.transcribe(req) { |r| puts "[#{r.task_status}] #{r.task_id}" }
    outputs.each_with_index do |out, i|
      puts "[音轨 #{i}] #{out.file.file_url}"
      out.file.transcripts.each do |t|
        (t['sentences'] || []).each { |s| puts "[#{s['begin_time']}-#{s['end_time']}ms] #{s['text']}" }
      end
    end

  when 'flash'
    req = DashScope::Transcription::FlashFileTranscriber::Request.new(
      model: maybe(o, 'model', default_model('flash')),
      audio: need(o, 'audio'),
      format: maybe(o, 'format', 'wav'),
      sample_rate: maybe(o, 'sample-rate', '0').to_i.then { |v| v.positive? ? v : nil }
    )
    client = DashScope::Transcription::FlashFileTranscriber.new(
      api_key: maybe(o, 'apikey', nil),
      url: maybe(o, 'url', 'https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation'),
      http_timeout: maybe(o, 'http-timeout', '120').to_f
    )
    if o.key?('stream')
      client.transcribe_streaming(req) do |r|
        puts "[定稿] #{r.sentence.text} (fixed=#{r.sentence.sentence_end})"
      end
    else
      r = client.transcribe(req)
      puts r.text
      r.sentence.words.first(3)&.each do |w|
        puts "[#{w.begin_time_ms}-#{w.end_time_ms}ms] #{w.text} (fixed=#{w.fixed.inspect})"
      end
    end

  when 'chat'
    model = maybe(o, 'model', default_model('chat'))
    chat = DashScope::Qwen::Conversation.new(
      api_key: maybe(o, 'apikey', nil),
      model: model,
      # 服务端默认音色不可靠（实测 qwen-audio 线不给 voice 会被判 does not exist），按模型线自动补
      voice: maybe(o, 'voice').then { |v|
        v.empty? ? (model == 'qwen3.8-omni-flash-realtime' ? 'Tina' : (DashScope::ModelRouting.qwen_audio_realtime_model?(model) ? 'longanfengyue_v3.1' : nil)) : v
      },
      instructions: maybe(o, 'instructions').then { |v| v.empty? ? nil : v },
      turn_detection_mode: o.key?('push-to-talk') ? :push_to_talk : :server_vad
    )
    chat.on_session_ready = ->(sid) { puts "[会话就绪 sess=#{sid}]" }
    chat.on_user_transcript_completed = ->(t, _) { puts "[我] #{t}" }
    chat.on_assistant_text_delta = ->(d, _) { print d }
    chat.on_assistant_text_completed = ->(t, _) { puts "\n[应答·文本完成] #{t}" }
    done = false
    chat.on_response_completed = lambda { |s|
      done = true
      puts "\n[本轮结束 status=#{s.status}#{s.failure_reason ? " reason=#{s.failure_reason}" : ''}]"
    }
    chat.on_error = ->(e) { warn "[error] #{e.server_error_message}" }
    output = maybe(o, 'output', 'response_24k.pcm')
    wait = maybe(o, 'wait-response', '60').to_f
    total = 0
    audio = maybe(o, 'audio')
    chat.connect
    if !audio.empty? && File.file?(audio)
      File.open(output, 'wb') do |out|
        chat.on_assistant_audio_chunk = ->(pcm) { out.write(pcm); total += pcm.bytesize }
        File.binread(audio).each_byte.each_slice(640).each do |slice|
          chat.append_audio(slice.pack('C*'))
          chat.pump(0.02)
        end
        # 补 ~1.6 秒静音让服务端 VAD 判尾（实测不补、或补量低于 silence_duration_ms，整轮悬着）
        8.times { chat.append_audio("\0" * 6400); chat.pump(0.2) }
        chat.pump_until(wait) { done }
      end
      puts "应答音频已写入 #{output}（#{total} 字节）" if total.positive?
    else
      chat.pump_until(wait) { done }
    end
    chat.finish

  when 'live'
    model = maybe(o, 'model', default_model('live'))
    front = maybe(o, 'front', 'qwen-audio-4.0-realtime-preview')
    live = DashScope::Qwen::Live.new(
      api_key: maybe(o, 'apikey', nil),
      model: model,
      front_model: front,
      # 音色必须与前台模型同线（实测跨线报 Unsupported voice）
      voice: maybe(o, 'voice').then { |v| v.empty? ? (front.start_with?('qwen-audio-4.0') ? 'yunshu' : 'longanfengyue_v3.1') : v },
      turn_detection_mode: front.start_with?('qwen-audio-4.0') ? :duplex : :server_vad,
      delegation: maybe(o, 'delegation', 'client').to_sym,
      responses_model: maybe(o, 'responses-model').then { |v| v.empty? ? nil : v },
      instructions: maybe(o, 'instructions').then { |v| v.empty? ? nil : v },
      stop_timeout: maybe(o, 'stop-timeout', '15').to_f
    )
    live.on_session_ready = ->(sid) { puts "[会话就绪 sess=#{sid}]" }
    live.on_user_transcript_delta = ->(t, _, _) { print "\r[我] #{t}          " }
    answer = +''
    live.on_assistant_text_delta = ->(t, _, _) { answer << t; print "\r[答] #{answer}          " }
    live.on_delegation_created = ->(s, _) { puts "\n[任务派发 #{s.delegation_id}] #{s.summary}" }
    live.on_backend_event = ->(t, root) { puts "\n[后台事件 #{t}] usage=#{root.dig('event', 'response', 'usage').inspect}" if t.include?('completed') }
    live.on_function_call = ->(cid, name, args) { puts "\n[前台函数 #{name} call=#{cid}] #{args}" }
    live.on_error = ->(e) { warn "\n[error] #{e.server_error_message}" }
    output = maybe(o, 'output', 'live_response_24k.pcm')
    wait = maybe(o, 'wait-response', '40').to_f
    total = 0
    audio = maybe(o, 'audio')
    text = maybe(o, 'text')
    File.delete(output) if File.exist?(output)
    live.connect
    File.open(output, 'wb') do |out|
      live.on_assistant_audio_chunk = ->(pcm, _, _) { out.write(pcm); total += pcm.bytesize }
      if !audio.empty? && File.file?(audio)
        # 16k 单声道 16bit：40ms = 1280 字节；duplex 会话须持续喂帧维持时间线
        File.binread(audio).bytes.each_slice(1280).each do |slice|
          live.append_audio(slice.pack('C*'))
          live.pump(0.04)
        end
        # 尾部补 ~1 秒静音帮助判尾
        25.times { live.append_audio("\0" * 1280); live.pump(0.04) }
      elsif !text.empty?
        live.send_user_text(text)
        puts '[提示] 实测文本项不触发前台语音回复，要听回答请 --audio 上行问句。'
      end
      # duplex 回复是流式的：等字幕连续 3s 不再增长（说完了）再 close，早关会掐断本轮
      t0 = Time.now
      prev = ''
      last_growth = t0
      while Time.now - t0 < wait
        live.pump(0.1)
        if answer != prev
          prev = answer.dup
          last_growth = Time.now
        elsif answer.length >= 4 && Time.now - last_growth > 3.0
          break
        end
        break if answer.empty? && Time.now - t0 > 25
      end
    end
    live.on_assistant_audio_chunk = nil # 文件已关：收尾阶段迟到的音频分片不再落盘
    live.finish
    u = live.usage
    puts "\n会话结束：计费 #{u&.seconds || '?'}s（按秒，最少 3s），应答音频 #{total} 字节 → #{output}。" unless u.nil? && total.zero?

  when 'translate'
    audio = need(o, 'audio')
    model = maybe(o, 'model', default_model('translate'))
    tr = DashScope::Qwen::Translator.new(
      api_key: maybe(o, 'apikey', nil),
      model: model,
      source_language: maybe(o, 'source', 'zh'),
      target_language: maybe(o, 'target', 'en'),
      voice: maybe(o, 'voice').then { |v| v.empty? ? (model == 'qwen3.8-livetranslate-flash-realtime' ? 'Serena' : nil) : v },
      transcription_model: maybe(o, 'asr-model').then { |v| v.empty? ? 'qwen3-asr-flash-realtime' : v }
    )
    tr.on_source_transcript_updated = ->(t, _) { print "\r[原文] #{t}          " }
    tr.on_source_transcript_completed = ->(t, _) { puts "\n[原文·定稿] #{t}" }
    tr.on_translation_text_delta = ->(d, _) { print d }
    tr.on_translation_completed = ->(t, _) { puts "\n[译文·定稿] #{t}" }
    tr.on_error = ->(e) { warn "[error] #{e.server_error_message}" }
    output = maybe(o, 'output', 'tr_24k.pcm')
    total = 0
    tr.on_translated_audio_chunk = ->(pcm) { File.open(output, 'ab') { |f| f.write(pcm) }; total += pcm.bytesize }
    File.delete(output) if File.exist?(output)
    tr.connect
    File.binread(audio).each_byte.each_slice(640).each do |slice|
      tr.append_audio(slice.pack('C*'))
      tr.pump(0.02)
    end
    tr.finish # 翻译面靠 finish 冲尾，不补静音也有译文
    puts "译文语音已写入 #{output}（#{total} 字节）"

  when 'models'
    face = maybe(o, 'face')
    if o.key?('names-only')
      VERIFIED.each { |r| puts r[:model] if r[:works] && (face.empty? || r[:face] == face) }
      exit 0
    end
    puts '百炼语音模型清单（本 demo 逐条真机验证；★ = 该命令 --model 默认值）'
    puts
    current = nil
    VERIFIED.each do |r|
      next unless face.empty? || r[:face] == face

      if r[:face] != current
        current = r[:face]
        puts "  #{current}  （dashscope #{current}）"
      end
      mark = r[:works] ? (r[:model] == default_model(r[:face]) ? '★' : ' ') : '✗'
      puts format('    %s %-42s %s', mark, r[:model], r[:note])
    end
    puts "\n  只看某一面：dashscope models --face asr"

  when '--help', '-h', 'help', nil, ''
    puts <<~TXT
      百炼(DashScope) C# SDK 的 Ruby 对等版 #{DashScope::Info::VERSION}

      用法: ruby bin/dashscope <command> [选项]   （API Key: --apikey sk-xxx 或环境变量 DASHSCOPE_API_KEY）

      命令: asr | tts | sambert | filetrans | flash | chat | live | translate | models
        sambert  --text "…" [--model sambert-zhichu-v1] [--sample-rate 16000] [--format wav|pcm|mp3]
                 [--word-timestamp 1] [--phoneme-timestamp 1]（音素须与字级同开；仅北京地域）
        chat     --audio 16k.pcm [--model …] [--voice …] [--push-to-talk] [--wait-response 60]
        live     --audio 16k.pcm [--front qwen-audio-4.0-realtime-preview] [--voice yunshu]
                 [--delegation client|responses] [--responses-model qwen4-max] [--output 24k.pcm]
                 （全双工会话：session.input_audio.append 上行，session.close 收尾，按秒计费）
        models   [--face asr|tts|sambert|filetrans|flash|chat|live|translate] [--names-only]
      其余命令选项见 C#/PHP 同名命令（报文与参数面一致）。
    TXT
    exit(cmd.nil? || cmd.empty? ? 1 : 0)
  else
    abort "未知命令: #{cmd}"
  end
rescue DashScope::Error => e
  warn "DashScope 错误 Code=#{e.code} ServerCode=#{e.server_error_code || '-'} " \
       "TaskId=#{e.task_id || e.request_id || '-'}: #{e.message}"
  exit 1
end
