#!/usr/bin/env bash
# =============================================================================
#  mxapi_h3_run.sh —— 用 MXAPI-AI 的 **MiniMax H3 在线接口**跑「源26《鸳鸯戏》日漫风 v2」
#
#  接口：POST https://open.mxapi.org/api/v2/video/minimax-h3
#        body: { model:"MiniMax-H3", content:[文本/图片/视频/音频],
#                resolution:"768P"|"2K", duration:4-15, ratio:"9:16", aigc_watermark:false }
#        查询：GET /api/v2/video/task?task_id=...
#
#  **计费（官方口径）**：768P 与 2K 分别 **50 / 80 积分/秒**，且 **输入视频的秒数同样计费**；
#        图片前 5 张免费、超出每张 20 积分；**音频免费**；提交时预扣、完成后多退少补、失败退还。
#
#  用法：
#     bash mxapi_h3_run.sh --dry-run                      # 只算钱 + 传资产，不提交
#     bash mxapi_h3_run.sh --resolution 2K --duration 15 --ref-video 15s --audio 15s
#     bash mxapi_h3_run.sh --resolution 768P --duration 10 --ref-video 10s --audio 10s
#   可选：--images anime|photoreal|none（默认 anime）  --ratio 9:16  --force（积分不足也提交）
# =============================================================================
set -uo pipefail
KEYFILE="/home/zyw/Downloads/mxapi_key.txt"
BASE="https://open.mxapi.org/api/v2"
ROOT="/home/zyw/Downloads/dl-hub/10-视频生成流水线/20261010_LMS荷塘月色_白模复刻"
ASSETS="$ROOT/MXAPI_H3"
ANIME_REFS="$ROOT/新角色A_日漫版_参考图"
REAL_REFS="$ROOT/新角色A_参考图"
OUTDIR="$ASSETS/out"; mkdir -p "$OUTDIR"
LOG="$ASSETS/mxapi_h3.log"
PROMPTFILE="$ROOT/prompt_角色A_源26竖屏_日漫风.txt"
UP="/home/zyw/Downloads/upload-image-public.sh"

RES="2K"; DUR=15; REFV="15s"; AUDS="15s"; IMGS="anime"; RATIO="9:16"; DRY=0; FORCE=0
while [ $# -gt 0 ]; do
  case "$1" in
    --resolution) RES="$2"; shift 2;;
    --duration)   DUR="$2"; shift 2;;
    --ref-video)  REFV="$2"; shift 2;;
    --audio)      AUDS="$2"; shift 2;;
    --images)     IMGS="$2"; shift 2;;
    --ratio)      RATIO="$2"; shift 2;;
    --dry-run)    DRY=1; shift;;
    --force)      FORCE=1; shift;;
    *) echo "未知参数 $1"; exit 2;;
  esac
done
log(){ echo "$(date '+%F %T') $*" | tee -a "$LOG"; }
K=$(cat "$KEYFILE")
api(){ curl -sS --noproxy '*' --max-time 60 -H "Authorization: Bearer $K" -H "Content-Type: application/json" "$@"; }

# ---------- 1) 算钱 ----------
RATE=50; [ "$RES" = "2K" ] && RATE=80
INV=0; [ "$REFV" = "15s" ] && INV=15; [ "$REFV" = "10s" ] && INV=10
NIMG=0; [ "$IMGS" != "none" ] && NIMG=2
OVER=$(( NIMG > 5 ? (NIMG-5)*20 : 0 ))
COST=$(( RATE * (INV + DUR) + OVER ))
BAL=$(api "$BASE/points/balance" | sed -n 's/.*"remaining_points":\([0-9]*\).*/\1/p')
log "配置：resolution=$RES duration=${DUR}s ratio=$RATIO ref_video=$REFV(${INV}s) audio=$AUDS images=$IMGS"
log "计费：${RATE} 积分/秒 × (输入视频 ${INV}s + 输出 ${DUR}s) + 图片超出 ${OVER} = **${COST} 积分**（$((COST/100)).$(printf %02d $((COST%100))) 元）"
log "当前余额：${BAL:-?} 积分"
if [ -n "${BAL:-}" ] && [ "$BAL" -lt "$COST" ] && [ "$FORCE" = "0" ]; then
  log "ABORT 余额不足：需 ${COST} 积分，现有 ${BAL}，**还需充值 $(( (COST-BAL+99)/100 )) 元档位以上**（1 元=100 积分）"
  [ "$DRY" = "1" ] || exit 3
fi

# ---------- 2) 参考资产上公网（每次现传，避免链接过期）----------
UPURLS=""
upload(){ # $1=本地文件 → $2=变量名
  local f="$1" r
  r=$(bash "$UP" "$f" | awk -F'\t' '{print $2}' | head -1)
  case "$r" in https://*) echo "$r";; *) echo "";; esac
}
IMG_ARGS=""
if [ "$IMGS" = "anime" ]; then
  U1=$(upload "$ANIME_REFS/charA_anime_face_threeview.png"); U2=$(upload "$ANIME_REFS/charA_anime_body_threeview.png")
elif [ "$IMGS" = "photoreal" ]; then
  U1=$(upload "$REAL_REFS/charA_face_threeview.jpg"); U2=$(upload "$REAL_REFS/charA_body_threeview.jpg")
fi
if [ "$IMGS" != "none" ]; then
  if [ -z "${U1:-}" ] || [ -z "${U2:-}" ]; then log "FAILED 参考图上公网失败（见图床脚本输出）"; exit 4; fi
  log "参考图URL：$U1 | $U2"
  IMG_ARGS="{\"type\":\"image_url\",\"image_url\":{\"url\":\"$U1\"},\"role\":\"reference_image\"},{\"type\":\"image_url\",\"image_url\":{\"url\":\"$U2\"},\"role\":\"reference_image\"},"
fi
VID_ARGS=""
if [ "$REFV" != "none" ]; then
  V1=$(upload "$ASSETS/m26ref_${REFV}_480x864.mp4")
  [ -n "$V1" ] || { log "FAILED 参考视频上公网失败"; exit 4; }
  log "参考视频URL：$V1"
  VID_ARGS="{\"type\":\"video_url\",\"video_url\":{\"url\":\"$V1\"},\"role\":\"reference_video\"},"
fi
AUD_ARGS=""
if [ "$AUDS" != "none" ]; then
  A1=$(upload "$ASSETS/m26audio_${AUDS}.m4a")
  [ -n "$A1" ] || { log "FAILED 参考音频上公网失败"; exit 4; }
  log "参考音频URL：$A1"
  AUD_ARGS="{\"type\":\"audio_url\",\"audio_url\":{\"url\":\"$A1\"},\"role\":\"reference_audio\"},"
fi

# ---------- 3) 提示词：资产对应关系 + 本地已验证的六段式（英文）----------
MAP="参考资产对应关系：<Video 1> 就是本次提交的 reference_video（白模舞蹈片，只提供动作/肢体运动/运镜/构图/时序，不提供任何外观）；<Picture 1> 是第 1 张 reference_image（同一角色的脸部三视图，身份/发型以此为准）；<Picture 2> 是第 2 张 reference_image（该角色全身三视图，身体比例与服装以此为准）。输出必须是日本动画赛璐璐（anime cel-shaded 2D）风格、竖屏 9:16、全身、无限无缝纯白摄影棚、画面里只有她一个人。以下为完整的六段式提示词："
TXT=$(cat "$PROMPTFILE" 2>/dev/null || true)
if [ -z "$TXT" ]; then
  log "WARN 提示词文件不可读（$PROMPTFILE），退回内置一句话提示词"
  TXT="Subject 2 replaces the white clay mannequin of Video 1: her face and hair come from Picture 1 and her body and costume come from Picture 2; the action, camera and timing follow Video 1; seamless pure-white studio; vertical 9:16; Japanese anime cel-shaded 2D rendering."
fi
PROMPT="$MAP

$TXT"
BODY=$(cat <<JSON
{
 "model": "MiniMax-H3",
 "content": [
  {"type":"text","text":$(printf '%s' "$PROMPT" | /usr/bin/python3 -c 'import json,sys;print(json.dumps(sys.stdin.read()))')},
  ${IMG_ARGS}${VID_ARGS}${AUD_ARGS}
  {"type":"text","text":"-"}
 ],
 "resolution": "$RES",
 "duration": $DUR,
 "ratio": "$RATIO",
 "aigc_watermark": false
}
JSON
)
BODY=$(printf '%s' "$BODY" | /usr/bin/python3 -c "import sys,json;d=json.load(sys.stdin);d['content']=[c for c in d['content'] if not (c.get('type')=='text' and c.get('text')=='-')];print(json.dumps(d,ensure_ascii=False))")
echo "$BODY" > "$ASSETS/last_request.json"
log "请求体已写入 $ASSETS/last_request.json"

if [ "$DRY" = "1" ]; then log "DRY-RUN 结束（未提交）"; exit 0; fi
if [ -n "${BAL:-}" ] && [ "$BAL" -lt "$COST" ] && [ "$FORCE" = "0" ]; then log "积分不足，未提交"; exit 3; fi

# ---------- 4) 提交 + 轮询 + 下载 ----------
RESP=$(api -X POST "$BASE/video/minimax-h3" -d "$BODY")
log "提交返回：$(printf '%s' "$RESP" | head -c 400)"
TID=$(printf '%s' "$RESP" | sed -n 's/.*"task_id":"\([^"]*\)".*/\1/p')
[ -n "$TID" ] || { log "FAILED 没拿到 task_id"; exit 5; }
log "task_id=$TID  开始轮询（每 10s，最多 40 分钟）"
for i in $(seq 1 240); do
  sleep 10
  Q=$(api "$BASE/video/task?task_id=$TID")
  ST=$(printf '%s' "$Q" | sed -n 's/.*"status":"\([^"]*\)".*/\1/p')
  [ $((i % 6)) -eq 0 ] && log "  [${i}0s] status=$ST"
  case "$ST" in
    completed)
      VURL=$(printf '%s' "$Q" | sed -n 's/.*"video_url":"\([^"]*\)".*/\1/p')
      log "完成：$VURL"
      DEST="$OUTDIR/20261012_H3online_源26_鸳鸯戏_角色A日漫风_${RES}_${DUR}s_${RATIO}.mp4"
      curl -sS --max-time 600 -o "$DEST" "$VURL" && log "已下载 $(ls -la "$DEST" | awk '{print $5}') 字节 → $DEST"
      BAL2=$(api "$BASE/points/balance" | sed -n 's/.*"remaining_points":\([0-9]*\).*/\1/p')
      log "余额变化：${BAL:-?} → ${BAL2:-?}（本次实际消耗 $(( ${BAL:-0} - ${BAL2:-0} )) 积分）"
      exit 0;;
    failed)
      log "FAILED 任务失败：$(printf '%s' "$Q" | head -c 500)"
      BAL2=$(api "$BASE/points/balance" | sed -n 's/.*"remaining_points":\([0-9]*\).*/\1/p')
      log "失败后余额：${BAL2:-?}（官方口径：失败自动退还）"
      exit 6;;
  esac
done
log "FAILED 轮询超时（40 分钟）"; exit 7
