#!/usr/bin/env bash
set -euo pipefail

manifest_path="${1:-}"
max_rows="${2:-3}"

if [[ -z "$manifest_path" || ! -f "$manifest_path" ]]; then
  echo "usage: $0 path/to/batch.tsv [max_rows]" >&2
  exit 2
fi

if ! [[ "$max_rows" =~ ^[1-9][0-9]*$ ]]; then
  echo "max_rows must be a positive integer" >&2
  exit 2
fi

command -v masonry >/dev/null || { echo "masonry CLI is required" >&2; exit 2; }
command -v jq >/dev/null || { echo "jq is required" >&2; exit 2; }

manifest_dir="$(cd "$(dirname "$manifest_path")" && pwd)"
job_log="$manifest_dir/kling-ai-cli-product-video-jobs.tsv"

if [[ ! -f "$job_log" ]]; then
  printf 'creative_id\tsku\tjob_id\tmodel\toutput_file\tcompleted_at_utc\n' > "$job_log"
fi

row_count=0
while IFS=$'\t' read -r creative_id sku source_image last_image model aspect audio_policy prompt output_file; do
  [[ "$creative_id" == "creative_id" ]] && continue
  [[ -z "$creative_id" ]] && continue

  row_count=$((row_count + 1))
  if (( row_count > max_rows )); then
    echo "refusing row $row_count: increase max_rows deliberately after reviewing cost and concurrency" >&2
    exit 3
  fi

  [[ -f "$source_image" ]] || { echo "missing source for $creative_id: $source_image" >&2; exit 4; }
  if [[ "$last_image" != "-" && ! -f "$last_image" ]]; then
    echo "missing last image for $creative_id: $last_image" >&2
    exit 4
  fi
  if [[ -e "$output_file" ]]; then
    echo "refusing to overwrite existing output for $creative_id: $output_file" >&2
    exit 5
  fi

  mkdir -p "$(dirname "$output_file")"
  command_args=(video "$prompt" --model "$model" --image "$source_image" --aspect "$aspect")
  [[ "$last_image" != "-" ]] && command_args+=(--last-image "$last_image")
  [[ "$audio_policy" == "off" ]] && command_args+=(--no-audio)

  submit_json="$(masonry "${command_args[@]}")"
  job_id="$(printf '%s' "$submit_json" | jq -er '.job_id')"
  masonry job wait "$job_id" --timeout 15m
  masonry job download "$job_id" --output "$output_file"

  printf '%s\t%s\t%s\t%s\t%s\t%s\n' \
    "$creative_id" "$sku" "$job_id" "$model" "$output_file" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" >> "$job_log"
done < "$manifest_path"

echo "completed $row_count row(s); job log: $job_log"
