/*
 * Copyright 2026, Jaime Terrats.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
export function transcriptionSkillMd(version) {
    return `---
name: transcription-evidence
version: "${version}"
description: Transcribe audio/video files and record as workflow evidence
inputs:
  - name: file
    description: Path to audio/video file (mp4, mp3, wav, m4a, webm)
    required: true
  - name: taskId
    description: Task ID to attach the evidence to
    required: true
  - name: role
    description: Role recording the evidence
    required: false
    default: qa
---

# Transcription Evidence Skill

Transcribes an audio or video file and records the transcript summary as evidence.

## Supported Formats

- Audio: mp3, wav, m4a, ogg, flac
- Video: mp4, webm, mkv (audio track extracted)

## Usage

\`\`\`bash
# With insanely-fast-whisper (fastest local option, GPU recommended)
insanely-fast-whisper --file-name <file> --transcript-path /tmp/transcript.json

# With faster-whisper (4x faster than original, CPU-friendly)
faster-whisper <file> --model medium --output_format txt

# With original Whisper
whisper <file> --model base --output_format txt --output_dir /tmp/transcripts

# With OpenAI API (requires OPENAI_API_KEY)
curl -s https://api.openai.com/v1/audio/transcriptions \\
  -H "Authorization: Bearer $OPENAI_API_KEY" \\
  -F file="@<file>" \\
  -F model="whisper-1" \\
  -F response_format="text"
\`\`\`

## Fallback Behavior

If no transcription API is available:
1. Check for \`insanely-fast-whisper\` CLI (pipx install insanely-fast-whisper)
2. Check for \`faster-whisper\` CLI (pip install faster-whisper)
3. Check for \`whisper\` CLI (pip install openai-whisper)
4. Check for \`OPENAI_API_KEY\` environment variable
5. If none available, record evidence with "transcription-pending" marker

## Evidence Recording

After transcription, record the result:

\`\`\`bash
sa-fast evidence add \\
  --task <taskId> \\
  --role <role> \\
  --type report \\
  --summary "Transcript of <filename>: <first 200 chars of transcript>"
\`\`\`
`;
}
export const TRANSCRIPTION_SUPPORTED_EXTENSIONS = ['.mp3', '.wav', '.m4a', '.ogg', '.flac', '.mp4', '.webm', '.mkv'];
const MAX_FILE_SIZE_MB = 200;
const CLOUD_MAX_OPENAI_MB = 25;
/**
 * Generates the `transcribe.sh` shell script that:
 * 1. Validates input (file exists, extension supported, size <= 200MB)
 * 2. For video files, extracts audio via ffmpeg
 * 3. Detects transcription backend in priority order
 * 4. Runs transcription, outputs UTF-8 .txt file
 * 5. Records evidence via orchestra CLI
 *
 * Exit codes: 0=success, 1=bad input, 2=too large, 3=no backend
 */
export function transcribeScript() {
    return `#!/usr/bin/env bash
set -euo pipefail

# ─── Transcription Evidence Script ────────────────────────────────────────────
# Generated by setup-agents. Do not edit manually.
#
# Usage: ./transcribe.sh <file> <taskId> [role]
# Exit codes: 0=success, 1=bad input, 2=file too large, 3=no backend available

FILE="\${1:-}"
TASK_ID="\${2:-}"
ROLE="\${3:-qa}"
MAX_SIZE_MB=${MAX_FILE_SIZE_MB}
SUPPORTED_EXT="mp3 wav m4a ogg flac mp4 webm mkv"

# ─── Input Validation ─────────────────────────────────────────────────────────

if [ -z "$FILE" ] || [ -z "$TASK_ID" ]; then
  echo "Usage: ./transcribe.sh <file> <taskId> [role]" >&2
  exit 1
fi

if [ ! -f "$FILE" ]; then
  echo "Error: File not found: $FILE" >&2
  exit 1
fi

EXT="\${FILE##*.}"
EXT_LOWER="$(echo "$EXT" | tr '[:upper:]' '[:lower:]')"
VALID=false
for ext in $SUPPORTED_EXT; do
  if [ "$EXT_LOWER" = "$ext" ]; then
    VALID=true
    break
  fi
done

if [ "$VALID" = false ]; then
  echo "Error: Unsupported extension .$EXT_LOWER. Supported: $SUPPORTED_EXT" >&2
  exit 1
fi

# ─── Size Check ───────────────────────────────────────────────────────────────

FILE_SIZE_MB=$(( $(wc -c < "$FILE") / 1048576 ))
if [ "$FILE_SIZE_MB" -gt "$MAX_SIZE_MB" ]; then
  echo "Error: File too large (\${FILE_SIZE_MB}MB > \${MAX_SIZE_MB}MB limit)" >&2
  exit 2
fi

# ─── Audio Extraction (video files) ──────────────────────────────────────────

AUDIO_FILE="$FILE"
VIDEO_EXT="mp4 webm mkv"
IS_VIDEO=false
for ext in $VIDEO_EXT; do
  if [ "$EXT_LOWER" = "$ext" ]; then
    IS_VIDEO=true
    break
  fi
done

if [ "$IS_VIDEO" = true ]; then
  if ! command -v ffmpeg >/dev/null 2>&1; then
    echo "Error: ffmpeg required for video files but not found in PATH" >&2
    exit 1
  fi
  AUDIO_FILE="/tmp/transcribe-audio-$$.wav"
  echo "Extracting audio from video..."
  ffmpeg -i "$FILE" -vn -acodec pcm_s16le -ar 16000 -ac 1 "$AUDIO_FILE" -y -loglevel error
fi

# ─── Backend Detection ────────────────────────────────────────────────────────

BACKEND=""
TRANSCRIPT_FILE="/tmp/transcript-$$.txt"

# Priority 1: whisper.cpp (whisper-cpp or whisper binary from whisper.cpp)
if command -v whisper-cpp >/dev/null 2>&1; then
  BACKEND="whisper-cpp"
elif command -v whisper >/dev/null 2>&1 && whisper --help 2>&1 | grep -q "whisper.cpp"; then
  BACKEND="whisper-cpp-alias"
# Priority 2: insanely-fast-whisper (Python, GPU)
elif command -v insanely-fast-whisper >/dev/null 2>&1; then
  BACKEND="insanely-fast-whisper"
# Priority 3: faster-whisper (Python, CPU)
elif command -v faster-whisper >/dev/null 2>&1; then
  BACKEND="faster-whisper"
# Priority 4: whisper from openai-whisper (Python)
elif command -v whisper >/dev/null 2>&1; then
  BACKEND="openai-whisper"
# Priority 5: Cloud fallback (opt-in)
elif [ -n "\${TRANSCRIBE_CLOUD_BACKEND:-}" ]; then
  BACKEND="cloud-\${TRANSCRIBE_CLOUD_BACKEND}"
fi

if [ -z "$BACKEND" ]; then
  echo "Warning: No transcription backend available." >&2
  echo "Install one of: whisper.cpp, insanely-fast-whisper, faster-whisper, openai-whisper" >&2
  echo "Or set TRANSCRIBE_CLOUD_BACKEND=openai|deepgram|assemblyai" >&2
  # Record pending evidence
  if command -v orchestra >/dev/null 2>&1; then
    orchestra evidence add --task "$TASK_ID" --role "$ROLE" --type report \\
      --summary "transcription-pending: no backend available for $(basename "$FILE")"
  fi
  exit 3
fi

echo "Using backend: $BACKEND"

# ─── Run Transcription ────────────────────────────────────────────────────────

case "$BACKEND" in
  whisper-cpp)
    whisper-cpp -f "$AUDIO_FILE" --output-txt -of "/tmp/transcript-$$"
    ;;
  whisper-cpp-alias)
    whisper -f "$AUDIO_FILE" --output-txt -of "/tmp/transcript-$$"
    ;;
  insanely-fast-whisper)
    insanely-fast-whisper --file-name "$AUDIO_FILE" --transcript-path "/tmp/transcript-$$.json"
    # Extract text from JSON output
    if command -v python3 >/dev/null 2>&1; then
      python3 -c "import json,sys; d=json.load(open('/tmp/transcript-$$.json')); print(d.get('text',''))" > "$TRANSCRIPT_FILE"
    else
      cat "/tmp/transcript-$$.json" > "$TRANSCRIPT_FILE"
    fi
    ;;
  faster-whisper)
    faster-whisper "$AUDIO_FILE" --model medium --output_format txt --output_dir /tmp
    mv "/tmp/$(basename "\${AUDIO_FILE%.*}").txt" "$TRANSCRIPT_FILE" 2>/dev/null || true
    ;;
  openai-whisper)
    whisper "$AUDIO_FILE" --model base --output_format txt --output_dir /tmp
    mv "/tmp/$(basename "\${AUDIO_FILE%.*}").txt" "$TRANSCRIPT_FILE" 2>/dev/null || true
    ;;
  cloud-openai)
    if [ -z "\${OPENAI_API_KEY:-}" ]; then
      echo "Error: OPENAI_API_KEY required for OpenAI cloud backend" >&2
      exit 1
    fi
    # OpenAI has ${CLOUD_MAX_OPENAI_MB}MB limit
    if [ "$FILE_SIZE_MB" -gt ${CLOUD_MAX_OPENAI_MB} ]; then
      echo "Error: File too large for OpenAI API (\${FILE_SIZE_MB}MB > ${CLOUD_MAX_OPENAI_MB}MB)" >&2
      exit 2
    fi
    curl -s https://api.openai.com/v1/audio/transcriptions \\
      -H "Authorization: Bearer $OPENAI_API_KEY" \\
      -F file="@$AUDIO_FILE" \\
      -F model="whisper-1" \\
      -F response_format="text" > "$TRANSCRIPT_FILE"
    ;;
  cloud-deepgram)
    if [ -z "\${DEEPGRAM_API_KEY:-}" ]; then
      echo "Error: DEEPGRAM_API_KEY required for Deepgram cloud backend" >&2
      exit 1
    fi
    curl -s https://api.deepgram.com/v1/listen \\
      -H "Authorization: Token $DEEPGRAM_API_KEY" \\
      -H "Content-Type: audio/*" \\
      --data-binary "@$AUDIO_FILE" | \\
      python3 -c "import json,sys; r=json.load(sys.stdin); print(r['results']['channels'][0]['alternatives'][0]['transcript'])" > "$TRANSCRIPT_FILE"
    ;;
  cloud-assemblyai)
    if [ -z "\${ASSEMBLYAI_API_KEY:-}" ]; then
      echo "Error: ASSEMBLYAI_API_KEY required for AssemblyAI cloud backend" >&2
      exit 1
    fi
    # Upload file
    UPLOAD_URL=$(curl -s https://api.assemblyai.com/v2/upload \\
      -H "authorization: $ASSEMBLYAI_API_KEY" \\
      --data-binary "@$AUDIO_FILE" | python3 -c "import json,sys; print(json.load(sys.stdin)['upload_url'])")
    # Request transcription
    TRANSCRIPT_ID=$(curl -s https://api.assemblyai.com/v2/transcript \\
      -H "authorization: $ASSEMBLYAI_API_KEY" \\
      -H "content-type: application/json" \\
      -d "{\\"audio_url\\": \\"$UPLOAD_URL\\"}" | python3 -c "import json,sys; print(json.load(sys.stdin)['id'])")
    # Poll for completion
    while true; do
      STATUS=$(curl -s "https://api.assemblyai.com/v2/transcript/$TRANSCRIPT_ID" \\
        -H "authorization: $ASSEMBLYAI_API_KEY" | python3 -c "import json,sys; d=json.load(sys.stdin); print(d['status']); open('$TRANSCRIPT_FILE','w').write(d.get('text','')) if d['status']=='completed' else None")
      if [ "$STATUS" = "completed" ]; then break; fi
      if [ "$STATUS" = "error" ]; then echo "Error: AssemblyAI transcription failed" >&2; exit 1; fi
      sleep 3
    done
    ;;
esac

# ─── Verify Output ────────────────────────────────────────────────────────────

if [ ! -f "$TRANSCRIPT_FILE" ] || [ ! -s "$TRANSCRIPT_FILE" ]; then
  echo "Error: Transcription produced no output" >&2
  exit 1
fi

# ─── Record Evidence ──────────────────────────────────────────────────────────

FILENAME="$(basename "$FILE")"
SUMMARY="$(head -c 500 "$TRANSCRIPT_FILE" | tr '\\n' ' ')"

if command -v orchestra >/dev/null 2>&1; then
  orchestra evidence add --task "$TASK_ID" --role "$ROLE" --type report \\
    --summary "Transcript of $FILENAME: $SUMMARY"
fi

echo "Transcription complete: $TRANSCRIPT_FILE"
echo "Backend used: $BACKEND"

# ─── Cleanup ──────────────────────────────────────────────────────────────────

if [ "$IS_VIDEO" = true ] && [ -f "$AUDIO_FILE" ]; then
  rm -f "$AUDIO_FILE"
fi
`;
}
//# sourceMappingURL=transcription-content.js.map