#!/bin/bash

# 微信公众号自动发布脚本（直接检测元素，不依赖URL）
# 用法: ./publish_to_wechat_mp.sh <markdown_file> <images_dir>

set -e

PROJECT_ROOT="/root/openclaw-workspace/projects/yu-zhi-ran"
SESSION_STATE="/root/openclaw-workspace/projects/yu-zhi-ran/automation/wechat_state.json"

if [ $# -ne 2 ]; then
  echo "用法: $0 <markdown_file> <images_dir>"
  exit 1
fi

MARKDOWN_FILE="$1"
IMAGES_DIR="$2"

echo "=========================================="
echo "微信公众号自动发布"
echo "=========================================="

# 1. 加载状态
agent-browser state load "$SESSION_STATE" 2>/dev/null || echo "⚠️  加载状态失败，但继续..."

# 2. 检测编辑器是否就绪（通过快照查找关键元素）
echo "检测编辑器页面..."
SNAPSHOT="/tmp/wechat_check_$(date +%s).json"
agent-browser snapshot -i --json > "$SNAPSHOT" 2>/dev/null || true

# 查找标题输入框和正文编辑器
HAS_TITLE=$(jq -r '.data.refs | to_entries[] | select(.value.role=="textbox" and (.value.name|test("标题|title";"i"))) | .key' "$SNAPSHOT" | head -1)
HAS_CONTENT=$(jq -r '.data.refs | to_entries[] | select(.value.role|test("textbox|generic") and (.value.name|test("内容|正文|editor";"i"))) | .key' "$SNAPSHOT" | head -1)

if [ -z "$HAS_TITLE" ] || [ -z "$HAS_CONTENT" ]; then
  echo "❌ 未检测到编辑器元素"
  echo "请确保："
  echo "  1. 已点击'新的创作' → '文章'"
  echo "  2. 编辑器已完全加载（看到标题输入框）"
  echo "  3. 编辑器标签页是当前活动标签页"
  echo ""
  echo "当前页面元素数: $(jq '.data.refs | length' "$SNAPSHOT" 2>/dev/null || echo 'unknown')"
  exit 3
fi

echo "✓ 编辑器就绪"
echo "  标题框: $HAS_TITLE"
echo "  正文框: $HAS_CONTENT"

# 3. 准备内容
ARTICLE_TITLE=$(head -1 "$MARKDOWN_FILE" | sed 's/^# //')
ARTICLE_BODY=$(sed '1d;$d' "$MARKDOWN_FILE")
COVER_IMG="$IMAGES_DIR/05-封面图.png"
[ -f "$COVER_IMG" ] || COVER_IMG=$(find "$IMAGES_DIR" -name "*封面*.png" -o -name "*cover*.png" | head -1)

echo "文章标题: $ARTICLE_TITLE"
echo "封面图: ${COVER_IMG:-未找到}"

# 4. 上传封面图（如果有）
if [ -f "$COVER_IMG" ]; then
  echo "上传封面图..."
  IMG_BTN=$(jq -r '.data.refs | to_entries[] | select(.value.name|test("图片|image|上传";"i")) | .key' "$SNAPSHOT" | head -1)
  if [ -n "$IMG_BTN" ]; then
    agent-browser click "@$IMG_BTN"
    sleep 2
    UPLOAD_INPUT=$(jq -r '.data.refs | to_entries[] | select(.value.role=="file") | .key' "$SNAPSHOT" | head -1)
    if [ -n "$UPLOAD_INPUT" ]; then
      agent-browser upload "@$UPLOAD_INPUT" "$COVER_IMG"
      sleep 3
    fi
  fi
fi

# 5. 填写标题
echo "填写标题..."
agent-browser fill "@$HAS_TITLE" "$ARTICLE_TITLE"
sleep 1

# 6. 填写正文（分段）
echo "填写正文..."
echo "$ARTICLE_BODY" | fold -s -w 80 | while IFS= read -r line; do
  [ -z "$line" ] && continue
  agent-browser fill "@$HAS_CONTENT" "$line"
  sleep 0.3
done

# 7. 截图
SCREENSHOT="$PROJECT_ROOT/content/published/$(date +%Y-%m-%d)-$(echo $ARTICLE_TITLE | tr -d '/*?\|"<>')/wechat-draft.png"
mkdir -p "$(dirname "$SCREENSHOT")"
agent-browser screenshot "$SCREENSHOT"
echo "截图: $SCREENSHOT"

# 8. 元数据
METADATA="$PROJECT_ROOT/content/published/$(date +%Y-%m-%d)-$(echo $ARTICLE_TITLE | tr -d '/*?\|"<>')/wechat-metadata.json"
cat > "$METADATA" <<EOF
{
  "title": "$ARTICLE_TITLE",
  "status": "draft",
  "filled_at": "$(date -Iseconds)"
}
EOF

echo "=========================================="
echo "✅ 内容填充完成！"
echo "请手动："
echo "  1. 点击'从正文选择'设置封面"
echo "  2. 填写摘要、标签"
echo "  3. 保存草稿"
echo "=========================================="
