#!/bin/bash

# 知乎自动发布脚本
# 用法: ./publish_to_zhihu.sh <markdown_file> <images_dir>
# 示例: ./publish_to_zhihu.sh content/drafts/001-optimized.md content/publishing/images

set -e

# 配置
PROJECT_ROOT="/root/openclaw-workspace/projects/yu-zhi-ran"
SESSION_STATE="/root/.openclaw/sessions/zhihu-state.json"
ZHIHU_CREATOR_URL="https://www.zhihu.com/creator"

# 参数检查
if [ $# -ne 2 ]; then
  echo "用法: $0 <markdown_file> <images_dir>"
  echo "示例: $0 content/drafts/001-optimized.md content/publishing/images"
  exit 1
fi

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

if [ ! -f "$MARKDOWN_FILE" ]; then
  echo "错误: Markdown文件不存在: $MARKDOWN_FILE"
  exit 1
fi

if [ ! -d "$IMAGES_DIR" ]; then
  echo "错误: 图片目录不存在: $IMAGES_DIR"
  exit 1
fi

echo "=========================================="
echo "知乎自动发布脚本"
echo "=========================================="
echo "Markdown: $MARKDOWN_FILE"
echo "图片目录: $IMAGES_DIR"
echo "会话状态: $SESSION_STATE"
echo ""

# 1. 加载登录状态
echo "步骤1: 加载知乎登录状态..."
agent-browser state load "$SESSION_STATE"

# 2. 打开创作中心
echo "步骤2: 打开知乎创作中心..."
agent-browser open "$ZHIHU_CREATOR_URL"
agent-browser wait --load networkidle

# 3. 检查是否遇到安全验证
echo "步骤3: 检查页面状态..."
CURRENT_URL=$(agent-browser get url)
if echo "$CURRENT_URL" | grep -q "unhuman"; then
  echo "⚠️  检测到安全验证页面！"
  echo "请在浏览器中手动完成验证，然后重新运行脚本。"
  echo "当前URL: $CURRENT_URL"
  echo ""
  echo "提示：如果经常触发验证，可以考虑："
  echo "  - 降低自动化频率"
  echo "  - 使用更稳定的网络环境"
  echo "  - 手动完成一次验证后，重新保存session状态"
  exit 2
fi

# 4. 获取页面快照，识别元素
echo "步骤4: 分析页面结构..."
SNAPSHOT_FILE="/tmp/zhihu_creator_$(date +%s).json"
agent-browser snapshot -i --json > "$SNAPSHOT_FILE"

# 5. 解析快照，查找按钮
echo "步骤5: 定位'新建文章'按钮..."
# 尝试多种定位策略
NEW_ARTICLE_REF=$(jq -r '.data.refs | to_entries[] | select(.value.name|test("新建|写文章|创作|new article|write";"i")) | .key' "$SNAPSHOT_FILE" | head -1)

if [ -z "$NEW_ARTICLE_REF" ] || [ "$NEW_ARTICLE_REF" = "null" ]; then
  echo "❌ 未找到'新建文章'按钮，可能需要手动操作"
  echo "快照文件: $SNAPSHOT_FILE"
  echo "请检查页面结构，更新脚本定位逻辑"
  exit 3
fi

echo "找到按钮引用: $NEW_ARTICLE_REF"

# 6. 点击新建文章
echo "步骤6: 点击新建文章..."
agent-browser click "@$NEW_ARTICLE_REF"
agent-browser wait --load networkidle
sleep 2

# 7. 解析文章编辑页面
echo "步骤7: 分析文章编辑页面..."
EDIT_SNAPSHOT="/tmp/zhihu_edit_$(date +%s).json"
agent-browser snapshot -i --json > "$EDIT_SNAPSHOT"

# 8. 提取标题输入框
TITLE_REF=$(jq -r '.data.refs | to_entries[] | select(.value.role=="textbox" and (.value.name|test("标题|title";"i"))) | .key' "$EDIT_SNAPSHOT" | head -1)

if [ -z "$TITLE_REF" ] || [ "$TITLE_REF" = "null" ]; then
  echo "⚠️  未找到标题输入框，尝试使用语义查找..."
  # 使用语义查找
  TITLE_REF=$(jq -r '.data.refs | to_entries[] | select(.value.role=="textbox") | .key' "$EDIT_SNAPSHOT" | head -1)
fi

# 9. 提取正文编辑器（通常是contenteditable或textarea）
CONTENT_REF=$(jq -r '.data.refs | to_entries[] | select(.value.role|in(["textbox","generic"];."name"|test("内容|content|正文|editor";"i"))) | .key' "$EDIT_SNAPSHOT" | head -1)

echo "定位结果:"
echo "  标题输入框: ${TITLE_REF:-未找到}"
echo "  正文编辑器: ${CONTENT_REF:-未找到}"

# 10. 准备文章内容
echo "步骤8: 准备文章内容..."
# 提取标题（第一行#后面的内容）
ARTICLE_TITLE=$(head -1 "$MARKDOWN_FILE" | sed 's/^# //')
echo "文章标题: $ARTICLE_TITLE"

# 提取正文（去掉标题和参考文献部分）
ARTICLE_BODY=$(sed '1d;$d' "$MARKDOWN_FILE")

# 11. 填写标题
if [ -n "$TITLE_REF" ] && [ "$TITLE_REF" != "null" ]; then
  echo "填写标题..."
  agent-browser fill "@$TITLE_REF" "$ARTICLE_TITLE"
  sleep 1
else
  echo "⚠️  跳过标题填写（需手动）"
fi

# 12. 填写正文
if [ -n "$CONTENT_REF" ] && [ "$CONTENT_REF" != "null" ]; then
  echo "填写正文（Markdown格式）..."
  agent-browser fill "@$CONTENT_REF" "$ARTICLE_BODY"
  sleep 2
else
  echo "⚠️  跳过正文填写（需手动）"
fi

# 13. 上传封面图
echo "步骤9: 处理封面图..."
COVER_IMG="$IMAGES_DIR/05-封面图.png"
if [ -f "$COVER_IMG" ]; then
  echo "找到封面图: $COVER_IMG"
  # 查找封面上传按钮
  COVER_REF=$(jq -r '.data.refs | to_entries[] | select(.value.name|test("封面|cover|图片|image";"i")) | .key' "$EDIT_SNAPSHOT" | head -1)
  if [ -n "$COVER_REF" ] && [ "$COVER_REF" != "null" ]; then
    echo "上传封面图..."
    agent-browser upload "@$COVER_REF" "$COVER_IMG"
    sleep 2
  else
    echo "⚠️  未找到封面上传按钮，需手动上传"
  fi
else
  echo "⚠️  未找到封面图文件"
fi

# 14. 标签和分类（可选，暂时跳过）
echo "步骤10: 标签和分类（需手动设置）"

# 15. 保存草稿
echo "步骤11: 保存草稿..."
# 查找保存按钮
SAVE_REF=$(jq -r '.data.refs | to_entries[] | select(.value.name|test("保存|save|草稿|draft";"i")) | .key' "$EDIT_SNAPSHOT" | head -1)

if [ -n "$SAVE_REF" ] && [ "$SAVE_REF" != "null" ]; then
  echo "点击保存草稿..."
  agent-browser click "@$SAVE_REF"
  agent-browser wait --load networkidle
  sleep 2
  echo "✅ 草稿已保存"
else
  echo "⚠️  未找到保存按钮，需手动保存"
fi

# 16. 截图确认
echo "步骤12: 截图确认..."
SCREENSHOT="$PROJECT_ROOT/content/published/$(date +%Y-%m-%d)-$(echo $ARTICLE_TITLE | tr -d '/*?\|"<>')/screenshot.png"
mkdir -p "$(dirname "$SCREENSHOT")"
agent-browser screenshot "$SCREENSHOT"
echo "截图保存至: $SCREENSHOT"

# 17. 记录发布信息
echo "步骤13: 记录元数据..."
METADATA_FILE="$PROJECT_ROOT/content/published/$(date +%Y-%m-%d)-$(echo $ARTICLE_TITLE | tr -d '/*?\|"<>')/metadata.json"
cat > "$METADATA_FILE" <<EOF
{
  "title": "$ARTICLE_TITLE",
  "markdown_file": "$MARKDOWN_FILE",
  "images_dir": "$IMAGES_DIR",
  "published_at": "$(date -Iseconds)",
  "status": "draft",
  "url": "待填写",
  "tags": [],
  "category": "待设置",
  "auto_filled": true,
  "notes": "自动化脚本填充草稿，需手动检查格式和发布"
}
EOF
echo "元数据保存至: $METADATA_FILE"

# 18. 完成
echo ""
echo "=========================================="
echo "✅ 发布流程完成！"
echo "=========================================="
echo "请手动检查："
echo "  1. 打开知乎创作中心，查看草稿"
echo "  2. 检查格式（Markdown渲染是否正确）"
echo "  3. 补充标签和分类"
echo "  4. 调整图片位置（如需）"
echo "  5. 预览并发布"
echo ""
echo "自动已完成："
echo "  ✓ 加载登录状态"
echo "  ✓ 打开创作中心"
echo "  ✓ 新建文章"
echo "  ✓ 填写标题和正文"
echo "  ✓ 上传封面图"
echo "  ✓ 保存草稿"
echo "  ✓ 截图确认"
echo ""
echo "快照文件保留:"
echo "  $SNAPSHOT_FILE"
echo "  $EDIT_SNAPSHOT"
echo "=========================================="
