#!/usr/bin/env bash
# Reads one public Instagram post so its hook can be studied without the user pasting anything.
# Usage: read-post.sh <instagram_url> <out_dir>
#   → <out_dir>/post.json (caption, author, metrics, surface), head.png (first 3 s, Reels),
#     sheet.png (whole Reel), transcript.json (first 10 s of speech, local Whisper).
# Exit 0 = read; 3 = Instagram asked for a login (see the message); 2 = usage or missing tool.
# Login is never automatic: set WIZZ_IG_COOKIES_BROWSER=<browser> (chrome, opera, safari...) only
# after the user agreed to use their own logged-in browser session for this read.
set -euo pipefail
[ $# -eq 2 ] || { echo "uso: read-post.sh <url do instagram> <pasta de saída>" >&2; exit 2; }
url="$1"; out="$2"
[[ "$url" =~ ^https://(www\.)?instagram\.com/([A-Za-z0-9._]+/)?(reel|reels|p|tv)/[A-Za-z0-9_-]+/?(\?.*)?$ ]] \
  || { echo "url inválida (esperado instagram.com/reel/..., /p/... ou /tv/...): $url" >&2; exit 2; }
for bin in yt-dlp ffmpeg node; do command -v "$bin" >/dev/null || { echo "falta $bin no PATH" >&2; exit 2; }; done
mkdir -p "$out"; cd "$out"
trap 'rm -f ./media.* ./head.wav ./raw.json.part' EXIT

auth=()
[ -n "${WIZZ_IG_COOKIES_BROWSER:-}" ] && auth=(--cookies-from-browser "$WIZZ_IG_COOKIES_BROWSER")
if ! yt-dlp -q --no-warnings --socket-timeout 20 ${auth[@]+"${auth[@]}"} -J "$url" > raw.json 2> err.txt; then
  if grep -qiE "login|cookies|empty media|not available" err.txt; then
    echo "O Instagram pediu login para este post. Opções: (1) com o OK do usuário, rodar de novo com WIZZ_IG_COOKIES_BROWSER=<navegador logado>; (2) print do post; (3) colar a legenda e o texto da tela." >&2
    exit 3
  fi
  cat err.txt >&2; exit 1
fi

# Caption, author and metrics; a carousel comes as a playlist of entries.
node - <<'JS'
const fs = require('node:fs');
const raw = JSON.parse(fs.readFileSync('raw.json', 'utf8'));
const entries = raw._type === 'playlist' ? raw.entries ?? [] : [raw];
const videos = entries.filter((e) => e && (e.vcodec && e.vcodec !== 'none' || e.duration));
const surface = raw._type === 'playlist' ? 'carrossel' : videos.length ? 'reel' : 'imagem';
const pick = (k) => raw[k] ?? entries[0]?.[k] ?? null;
fs.writeFileSync('post.json', JSON.stringify({
  url: raw.webpage_url ?? raw.original_url,
  surface,
  slides: raw._type === 'playlist' ? entries.length : 1,
  author: pick('uploader') ?? pick('channel'),
  handle: pick('channel') ?? pick('uploader_id'),
  date: pick('upload_date'),
  caption: pick('description') ?? '',
  likes: pick('like_count'),
  comments: pick('comment_count'),
  views: pick('view_count'),
  duration_s: pick('duration'),
}, null, 1));
JS
rm -f raw.json err.txt

surface=$(node -p "require('./post.json').surface")
if [ "$surface" = "reel" ]; then
  yt-dlp -q --no-warnings --socket-timeout 20 ${auth[@]+"${auth[@]}"} -o "media.%(ext)s" "$url"
  media=$(ls media.* | head -1)
  ffmpeg -loglevel error -y -t 3 -i "$media" -vf "fps=2,scale=270:-1,tile=6x1" -frames:v 1 head.png
  d=$(ffprobe -v error -show_entries format=duration -of csv=p=0 "$media")
  step=$(node -p "Math.max(1, $d / 8)")
  ffmpeg -loglevel error -y -i "$media" -vf "fps=1/$step,scale=270:-1,tile=8x1" -frames:v 1 sheet.png
  if ffmpeg -loglevel error -y -t 10 -i "$media" -vn -ac 1 -ar 16000 head.wav 2>/dev/null; then
    # Local Whisper through the HyperFrames CLI: no API key. Multilingual model, Portuguese by default.
    npx -y hyperframes transcribe head.wav -d . -m small -l "${WIZZ_IG_LANG:-pt}" --json >/dev/null 2>transcribe.log \
      || echo "transcrição falhou (ver transcribe.log); siga pelos quadros e pela legenda" >&2
    # Whisper invents words over music with no speech ("Thank you for watching", "Legendas pela
    # comunidade"): stretched words or too few words per second mean there was no real speech.
    [ -f transcript.json ] && node - <<'JS'
const fs = require('node:fs');
const raw = JSON.parse(fs.readFileSync('transcript.json', 'utf8'));
const words = Array.isArray(raw) ? raw : raw.words ?? [];
const span = words.length ? words.at(-1).end - words[0].start : 0;
const stretched = words.some((w) => w.end - w.start > 1.2);
const slow = span > 0 && words.length / span < 0.8;
const canned = /thank you for watching|obrigad[oa] por assistir|legendas? pela comunidade|inscreva-se/i.test(words.map((w) => w.text).join(' '));
const post = JSON.parse(fs.readFileSync('post.json', 'utf8'));
post.speech = words.length === 0 ? 'sem fala' : stretched || slow || canned ? 'suspeita' : 'ok';
fs.writeFileSync('post.json', JSON.stringify(post, null, 1));
if (post.speech !== 'ok') console.error(`transcrição ${post.speech}: provavelmente música sem fala; o gancho está nos quadros e no texto da tela`);
JS
  else
    echo "Reel sem áudio: o gancho está só no texto da tela (head.png)" >&2
  fi
fi
echo "ok: $(pwd)/post.json ($surface)"
