#!/usr/bin/env bash
set -euo pipefail

json_error() {
  STAGE="$1" RAW="$2" python3 - <<'PY'
import os, json
print(json.dumps({
  "ok": False,
  "stage": os.environ["STAGE"],
  "raw": os.environ["RAW"],
}, ensure_ascii=False))
PY
}

work_dir=/tmp/wechat_draft_test_work
mkdir -p "$work_dir"

TITLE=$(python3 -c 'import os,base64; print(base64.b64decode(os.environ["TITLE_BASE64"]).decode("utf-8"))')
CONTENT=$(python3 -c 'import os,base64; print(base64.b64decode(os.environ["CONTENT_BASE64"]).decode("utf-8"))')
TOKEN=$(python3 -c 'import os,json,urllib.request,urllib.parse; appid=os.environ["APPID"]; secret=os.environ["SECRET"]; url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s"%(urllib.parse.quote(appid),urllib.parse.quote(secret)); print(json.load(urllib.request.urlopen(url, timeout=20))["access_token"])')
TOKEN="$TOKEN" python3 -c 'import os,json,urllib.request,urllib.parse; url="https://api.weixin.qq.com/cgi-bin/account/getaccountbasicinfo?access_token=%s"%urllib.parse.quote(os.environ["TOKEN"]); open("/tmp/wechat_draft_test_work/account_info.json","w").write(json.dumps(json.load(urllib.request.urlopen(url, timeout=20)), ensure_ascii=False))'

thumb_file=/tmp/wechat_thumb_real.jpg
if [ ! -f "$thumb_file" ]; then
  json_error "missing_thumb" "missing /tmp/wechat_thumb_real.jpg"
  exit 2
fi

curl -sS --max-time 30 -F media=@"$thumb_file" "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=${TOKEN}&type=image" > "$work_dir/upload_response.json"
if ! THUMB_MEDIA_ID=$(python3 -c 'import json; data=json.load(open("/tmp/wechat_draft_test_work/upload_response.json")); print(data["media_id"])' 2>/dev/null); then
  json_error "upload_thumb" "$(cat "$work_dir/upload_response.json")"
  exit 2
fi

DRAFT_PAYLOAD=$(TITLE="$TITLE" CONTENT="$CONTENT" THUMB_MEDIA_ID="$THUMB_MEDIA_ID" python3 -c 'import os,json; print(json.dumps({"articles":[{"title":os.environ["TITLE"],"author":"Mason","digest":"科技向自动路由草稿测试","content":os.environ["CONTENT"],"content_source_url":"","thumb_media_id":os.environ["THUMB_MEDIA_ID"],"need_open_comment":0,"only_fans_can_comment":0}]}, ensure_ascii=False))')
curl -sS --max-time 30 -H 'Content-Type: application/json' -d "$DRAFT_PAYLOAD" "https://api.weixin.qq.com/cgi-bin/draft/add?access_token=${TOKEN}" > "$work_dir/draft_add_response.json"
if ! MEDIA_ID=$(python3 -c 'import json; data=json.load(open("/tmp/wechat_draft_test_work/draft_add_response.json")); print(data["media_id"])' 2>/dev/null); then
  json_error "draft_add" "$(cat "$work_dir/draft_add_response.json")"
  exit 2
fi

BATCH_PAYLOAD='{"offset":0,"count":20,"no_content":0}'
curl -sS --max-time 30 -H 'Content-Type: application/json' -d "$BATCH_PAYLOAD" "https://api.weixin.qq.com/cgi-bin/draft/batchget?access_token=${TOKEN}" > "$work_dir/draft_batchget_response.json"

MEDIA_ID="$MEDIA_ID" python3 - <<'PY'
import os, json
account_info = json.load(open("/tmp/wechat_draft_test_work/account_info.json"))
upload_resp = json.load(open("/tmp/wechat_draft_test_work/upload_response.json"))
add_resp = json.load(open("/tmp/wechat_draft_test_work/draft_add_response.json"))
batch_resp = json.load(open("/tmp/wechat_draft_test_work/draft_batchget_response.json"))
media_id = os.environ["MEDIA_ID"]
verified = False
matched = None
for item in batch_resp.get("item", []):
    if item.get("media_id") == media_id:
        verified = True
        matched = item
        break
print(json.dumps({
    "ok": True,
    "account_info": account_info,
    "upload_response": upload_resp,
    "draft_add_response": add_resp,
    "batchget_matched": matched,
    "verified_in_batchget": verified
}, ensure_ascii=False))
PY
