#!/usr/bin/env bash
# mojeek.sh — Consulta Mojeek AI summary sin navegador
# Uso: ./mojeek.sh "tu pregunta aquí"

QUERY="${1:-por que monero es mejor que bitcoin}"
ENCODED=$(python3 -c "import urllib.parse,sys; print(urllib.parse.quote_plus(sys.argv[1]))" "$QUERY")
UA="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36"

echo "🔍 Buscando: $QUERY"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

HTML=$(curl -s -A "$UA" -H "Accept-Encoding: identity" \
  "https://www.mojeek.com/search?q=${ENCODED}&fmt=summary")

KALID=$(echo "$HTML" | grep -oP 'data-suid="\K[a-f0-9]+' | head -1)

if [[ -z "$KALID" ]]; then
  echo "❌ No se pudo obtener el kalid."
  echo "$HTML" > /tmp/mojeek_debug.html
  exit 1
fi

echo "✅ kalid: $KALID"
echo ""
echo "📡 Respuesta:"
echo ""

curl -s -N -A "$UA" \
  -H "Accept: text/event-stream" \
  -H "Referer: https://www.mojeek.com/" \
  "https://www.mojeek.com/llm/streamResponse?kalid=${KALID}&q=${ENCODED}" \
| python3 -c "
import sys, json, re

full = ''
for line in sys.stdin:
    line = line.strip()
    if not line.startswith('data:'):
        continue
    payload = line[5:].strip()
    if not payload or payload[0] in ('\"', '['):
        continue
    try:
        obj = json.loads(payload)
        choices = obj.get('choices', [])
        if not choices:
            continue
        content = choices[0].get('delta', {}).get('content', '')
        if content:
            full += content
        if choices[0].get('finish_reason') == 'stop':
            break
    except:
        pass

full = re.sub(r'\[citation:[\d,\s]+\]', '', full)
print(full)
"

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"