#!/usr/bin/env bash
# 偶合 OppHub · opphub cron 通道选择配置 (v2.9.0 老板 21:15+21:20+21:24 拍板)
#
# 老板反馈 (21:15): 不需要去 OPPHUB 绑通道, 查 openclaw 已装, 让用户选
# 老板追问 (21:20): 选 agent 还是选群, 微信怎么弄
# 老板方案 A (21:24): WeChat 插件注册默认 target, announce targetless 也行
#
# 逻辑:
#   1. openclaw channels list --json → 拿已装 + 账号
#   2. 让用户选四种 target:
#        <type>:<account>        feishu:dev
#        <type>:agent:<id>       feishu:agent:ceo
#        <type>:group:<chat_id>  feishu:group:oc_xxxx
#        <type>                  targetless (老板方案 A)
#   3. 用 OpenClaw cron add 建, 模仿老板『每日工作汇报』格式

_opphub_resolve_link() {
  readlink -f "$1" 2>/dev/null     || python3 -c "import os,sys; print(os.path.realpath(sys.argv[1]))" "$1" 2>/dev/null     || echo "$1"
}

_SCRIPT_REAL=$(_opphub_resolve_link "${BASH_SOURCE[0]}")
SCRIPT_DIR="$(cd "$(dirname "$_SCRIPT_REAL")" && pwd)"
source "$SCRIPT_DIR/../lib/opphub-paths.sh"
opphub_init_home
source "$SCRIPT_DIR/../lib/opphub-schema.sh"
source "$SCRIPT_DIR/../lib/opphub-cron.sh"

set -e

JSON_OUT=true
DRY_RUN=false
AUTO_MODE=false
PICKED=""
LIST_KIND="installed"

while [ $# -gt 0 ]; do
  case "$1" in
    --json) JSON_OUT=true; shift ;;
    --human) JSON_OUT=false; shift ;;
    --auto) AUTO_MODE=true; shift ;;
    --dry-run) DRY_RUN=true; shift ;;
    --pick) PICKED="$2"; shift 2 ;;
    --list-all) LIST_KIND="all"; shift ;;
    --help|-h)
      cat << 'USAGE'
opphub cron-setup — OpenClaw 通道 cron 配置 (v2.9.0)

四种 pick 格式:
  <type>:<account>         账号型    feishu:dev
  <type>:agent:<id>        代理型    feishu:agent:ceo
  <type>:group:<chat_id>   群型      feishu:group:oc_xxx
  <type>                   targetless  feishu / weixin (老板方案 A)

用法:
  opphub cron-setup --json
  opphub cron-setup --pick feishu:group:oc_xxx --auto
  opphub cron-setup --pick weixin  (targetless)
USAGE
      exit 0 ;;
    *) json_error cron_setup_args BAD_REQUEST "未知参数: $1" ;;
  esac
done

require_bot_mode

# Step 1: OpenClaw channels list
if [ "$LIST_KIND" = "all" ]; then
  CHANNELS_JSON=$(timeout 8 openclaw channels list --all --json 2>/dev/null)
else
  CHANNELS_JSON=$(timeout 8 openclaw channels list --json 2>/dev/null)
fi

if [ -z "$CHANNELS_JSON" ]    || ! echo "$CHANNELS_JSON" | python3 -c "import json,sys; json.load(sys.stdin)" 2>/dev/null; then
  json_error cron_setup NO_OPENCLAW_CHANNELS "openclaw channels list --json 返空, 跑 openclaw doctor"
fi

# Step 1.5: 解析用 python -c + stdin (避免 heredoc 冲突)
INSTALLED_JSON=$(echo "$CHANNELS_JSON" | python3 -c '
import json, sys
try:
    d = json.load(sys.stdin)
    chat = d.get("chat") or {}
    catalog = d.get("catalog") or {}
    out = []
    for ch_type, ch_data in chat.items():
        if not isinstance(ch_data, dict): continue
        if not ch_data.get("installed"): continue
        accounts = ch_data.get("accounts") or []
        out.append({"type": ch_type, "status": "installed", "accounts": accounts})
    for ch_type, ch_data in catalog.items():
        if ch_type in [o["type"] for o in out]: continue
        if not isinstance(ch_data, dict): continue
        out.append({"type": ch_type, "status": "installable", "accounts": []})
    print(json.dumps(out, ensure_ascii=False))
except Exception as e:
    print("[]", file=sys.stderr)
' 2>/dev/null)

TOTAL_INSTALLED=$(echo "$INSTALLED_JSON" | python3 -c "import json,sys; print(sum(1 for o in json.load(sys.stdin) if o.get('status')=='installed'))")
TOTAL_INSTALLABLE=$(echo "$INSTALLED_JSON" | python3 -c "import json,sys; print(sum(1 for o in json.load(sys.stdin) if o.get('status')=='installable'))")

# Step 1.6: 看现状 cron
CURRENT_OPPHUB_CRON=$(timeout 8 openclaw cron list --json 2>/dev/null | python3 << 'PYEOF'
import json, sys
try:
    d = json.load(sys.stdin)
    for j in d.get('jobs', []):
        if 'opphub' in j.get('name', '').lower() and 'check' in j.get('name', '').lower():
            print(json.dumps({
                'id': j['id'],
                'name': j['name'],
                'delivery': j.get('delivery'),
                'lastStatus': j.get('state', {}).get('lastDeliveryStatus'),
            }, ensure_ascii=False))
            break
except Exception:
    pass
PYEOF
)

# Step 2/3: 给用户选
if [ "$PICKED" = "" ]; then
  cat <<EOF
{
  "ok": true,
  "step": "cron_setup",
  "code": "AWAITING_PICK",
  "message": "本机已装 $TOTAL_INSTALLED 个通道 (可装 $TOTAL_INSTALLABLE, 微信需 openclaw plugins install)",
  "installed_channels": $INSTALLED_JSON,
  "current_opphub_cron": $(echo "$CURRENT_OPPHUB_CRON" | python3 -c "
import json, sys
try:
    d = json.loads(sys.stdin.read())
    print(json.dumps(d, ensure_ascii=False))
except Exception:
    print('null')
" 2>/dev/null || echo "null"),
  "weixin_targetless_hint": {
    "note": "老板方案 A (21:24): WeChat 插件注册时存默认 target, announce 不传 to 也能发",
    "this_skill_supports": "opphub cron-setup --pick weixin (targetless)",
    "openclaw_runtime_fix_needed": "openclaw-weixin plugin 存 defaultTarget, announce 不强要 --to",
    "side_note": "本 skill 不能改 OpenClaw runtime. 提供 --pick <type> targetless 语法, 等 plugin 改完就能跑"
  },
  "suggestion": "opphub cron-setup --pick feishu:group:oc_dd4af9cd62b2914c21ae52bbcacc6474 (推荐)"
}
EOF
  exit 0
fi

# Step 4: 解析 --pick
# Parse PICKED into PICK_TYPE + REST.
# PICK_TYPE 始终是第一个 : 前段.
# REST 是 PICK_TYPE 后面的整段 (可能含 :). 例:
#   feishu                  -> PICK_TYPE=feishu, REST=""
#   feishu:dev              -> PICK_TYPE=feishu, REST=dev
#   feishu:group:oc_xxx     -> PICK_TYPE=feishu, REST=group:oc_xxx
#   feishu:agent:ceo        -> PICK_TYPE=feishu, REST=agent:ceo
PICK_TYPE=$(echo "$PICKED" | cut -d: -f1)
REST=$(echo "$PICKED" | awk -F: '{if(NF==1) print ""; else {out=""; for(i=2;i<=NF;i++){out=out (i>2?":":"") $i}; print out}}')

TARGET_KIND=""
TARGET=""
TO_ARG=""
AGENT_ID=""
CHANNEL_ARG="$PICK_TYPE"

if [ -z "$REST" ]; then
  # targetless
  IS_INSTALLED=$(echo "$INSTALLED_JSON" | python3 -c "
import json, sys
for o in json.load(sys.stdin):
    if o.get('type') == '$PICK_TYPE':
        print(o.get('status'))
        break
")
  if [ "$IS_INSTALLED" != "installed" ]; then
    AVAILABLE=$(echo "$INSTALLED_JSON" | python3 -c "import json,sys; print(','.join(o['type'] for o in json.load(sys.stdin) if o.get('status')=='installed'))")
    json_error cron_setup CHANNEL_NOT_INSTALLED "通道 $PICK_TYPE 未装 (已装: $AVAILABLE)"
  fi
  TARGET_KIND="targetless"
elif echo "$REST" | grep -qE "^agent:" ; then
  TARGET=$(echo "$REST" | sed 's/^agent://')
  if [ -z "$TARGET" ]; then json_error cron_setup BAD_PICK "格式错 :agent:<id>"; fi
  TARGET_KIND="agent"
  AGENT_ID="$TARGET"
elif echo "$REST" | grep -qE "^group:" ; then
  TARGET=$(echo "$REST" | sed 's/^group://')
  if [ -z "$TARGET" ]; then json_error cron_setup BAD_PICK "格式错 :group:<chat_id>"; fi
  TARGET_KIND="group"
  TO_ARG="$TARGET"
else
  # 账号
  VALID_ACCT=$(echo "$INSTALLED_JSON" | python3 -c "
import json, sys
for o in json.load(sys.stdin):
    if o.get('type') == '$PICK_TYPE':
        if '$REST' in o.get('accounts', []):
            print('ok')
        else:
            print(o.get('accounts', []))
        break
")
  if [ "$VALID_ACCT" != "ok" ]; then
    json_error cron_setup ACCOUNT_NOT_FOUND "账号 $REST 不在 $PICK_TYPE, 已有: $VALID_ACCT"
  fi
  TARGET_KIND="account"
  TARGET="$REST"
  TO_ARG="$REST"
fi

# Step 5: 构建 openclaw cron add 命令
expr=$(_opphub_cron_get_expr)
tz=$(_opphub_cron_get_tz)
# 2026-07-08: cron 任务改指向 opphub-daily-digest (检查更新 + 商机 + 状态 中文化)
skill_bin="$(cd "$(dirname "$_SCRIPT_REAL")/.." && pwd)/bin/opphub-daily-digest"
skill_bin_legacy="$(cd "$(dirname "$_SCRIPT_REAL")/.." && pwd)/bin/opphub-check-update"

CRON_ARGV=("openclaw" "cron" "add"
  "--name" "$CRON_JOB_NAME"
  "--cron" "$expr"
  "--tz" "$tz"
  "--session" "isolated"
  "--command" "$skill_bin"
  "--channel" "$CHANNEL_ARG"
  "--best-effort-deliver"
  "--timeout-seconds" "300")

if [ -n "$TO_ARG" ]; then CRON_ARGV+=("--to" "$TO_ARG"); fi
if [ -n "$AGENT_ID" ]; then CRON_ARGV+=("--agent" "$AGENT_ID"); fi

# Step 6: dry-run
if [ "$DRY_RUN" = "true" ]; then
  ARGV_JSON=$(python3 -c "import json,sys; print(json.dumps(sys.argv[1:], ensure_ascii=False))" "${CRON_ARGV[@]}")
  cat <<EOF
{
  "ok": true,
  "step": "cron_setup",
  "dry_run": true,
  "channel_type": "$PICK_TYPE",
  "target_kind": "$TARGET_KIND",
  "target": "$TARGET",
  "to_arg": "$TO_ARG",
  "agent_id": "$AGENT_ID",
  "openclaw_cron_add": $ARGV_JSON
}
EOF
  exit 0
fi

# Step 7: 强提示检查
if ! opphub_cron_check_setup >/dev/null 2>&1; then
  json_error cron_setup NO_CHANNEL_ENV "未检测到 IM 通道, 跑 openclaw doctor"
fi

# Step 7.5: 2026-07-08 检查已有 cron 任务是否需要更新
NEEDS_UPDATE_JSON=$(opphub_cron_needs_update "$expr" "$tz" "$skill_bin" 2>/dev/null || echo '{"needs_update": false}')
HAS_DAILY_DIGEST=$(echo "$NEEDS_UPDATE_JSON" | python3 -c 'import json,sys; d=json.load(sys.stdin); print("1" if d.get("needs_update") else "0")' 2>/dev/null || echo "0")
CRON_ACTION="created"
if opphub_cron_exists 2>/dev/null; then
  CRON_ACTION="unchanged"
  # 任务已存在 —检查是否要更新 (刷换成 daily-digest)
  if [ "$HAS_DAILY_DIGEST" = "1" ]; then
    CRON_ACTION="recreated"
    # bot mode: 不提示, 直接重建
    if [ "$AUTO_MODE" = "true" ] || [ "$JSON_OUT" = "true" ]; then
      : # 静默重建
    else
      echo "[opphub-cron-setup] 检测到 cron 任务内容已变更 (加商机推送 + 全中文化), 准备重建..." >&2
    fi
  fi
fi

# Step 8: 按 jobId 删全部同名旧 job (openclaw cron rm 只接 jobId, 不接 --name)
# ★ 2026-07-08 老板反馈: 之前 Step 8 用 --name 是 bug, 静默失败导致 N 条同名 job 残留
# ★ 2026-07-08 老板追问: 加了 needs_update 判断后仍多条, 原因是 OpenClaw cron list 有延迟
#   (add 完几秒内 list 查不到), 两次连续跑会走"不存在→created→又 add" 的路径.
#   幂等保证 = 任何情况 add 完都按 jobId 删剩余同名 job, 只留最后这条.
if [ "$CRON_ACTION" = "recreated" ]; then
  # 列所有同名 job 的 id 一次性全删
  REMOVE_IDS=$(timeout 8 openclaw cron list --all --json 2>/dev/null | python3 << 'PYEOF'
import json, sys, re
raw = sys.stdin.read()
m = re.search(r'\{[\s\S]*\}', raw)
if not m: sys.exit(0)
try:
    d = json.loads(m.group())
except Exception:
    sys.exit(0)
name = 'opphub-skill-daily-check'
ids = [j['id'] for j in d.get('jobs', []) if j.get('name') == name and j.get('id')]
print(' '.join(ids))
PYEOF
)
  REMOVED_COUNT=0
  for jid in $REMOVE_IDS; do
    if timeout 8 openclaw cron rm "$jid" >/dev/null 2>&1; then
      REMOVED_COUNT=$((REMOVED_COUNT + 1))
    fi
  done
  if [ "$JSON_OUT" = "true" ] || [ "$AUTO_MODE" = "true" ]; then
    : # 静默
  else
    echo "[opphub-cron-setup] 已删 $REMOVED_COUNT 条旧同名 job" >&2
  fi
fi

"${CRON_ARGV[@]}" 2>&1

# Step 8.5 (★ 2026-07-08 老板追问后加的幂等性最终保证): add 完删全部其他同名 job
# 不管前面的判断是不是被 cron list 延迟骗了, 这一步保底.
# add 命令返的最后一条 job id 拿不到, 所以退而求其次: 删全部同名, 再 add 一次.
# 但这样会下路建 2 次 (先 add, 删, 再 add). 优化: 拿 add 输出里的 jobId, 只删其他.
ADD_OUTPUT=$("${CRON_ARGV[@]}" 2>&1)
# 从 add 输出里抓 jobId
ADDED_ID=$(echo "$ADD_OUTPUT" | python3 -c "
import json, sys, re
raw = sys.stdin.read()
m = re.search(r'\{[\s\S]*\}', raw)
if not m: sys.exit(0)
try:
    d = json.loads(m.group())
except Exception:
    sys.exit(0)
# add 返回可能是 { 'job': {...} } 或 { 'id': '...' } 或其他
job = d.get('job') or d
print(job.get('id') or '')
" 2>/dev/null)
# 列出现有所有同名 job id, 跳过我刚 add 的那条, 删剩余的
DEDUP_OUTPUT=$(timeout 8 openclaw cron list --all --json 2>/dev/null)
DEDUP_IDS=$(echo "$DEDUP_OUTPUT" | python3 -c "
import json, sys, re
raw = sys.stdin.read()
m = re.search(r'\{[\s\S]*\}', raw)
if not m: sys.exit(0)
try:
    d = json.loads(m.group())
except Exception:
    sys.exit(0)
keep = '$ADDED_ID'
out = []
for j in d.get('jobs', []):
    if j.get('name') == 'opphub-skill-daily-check' and j.get('id') and j['id'] != keep:
        out.append(j['id'])
print(' '.join(out))
" 2>/dev/null)
DEDUP_REMOVED=0
for jid in $DEDUP_IDS; do
  if timeout 8 openclaw cron rm "$jid" >/dev/null 2>&1; then
    DEDUP_REMOVED=$((DEDUP_REMOVED + 1))
  fi
done

# 调整 action 表达
if [ "$CRON_ACTION" = "created" ] && [ -n "$ADDED_ID" ]; then
  CRON_ACTION="created"
elif [ "$CRON_ACTION" = "unchanged" ] && [ "$DEDUP_REMOVED" -gt 0 ]; then
  CRON_ACTION="deduped"
fi

cat <<EOF
{
  "ok": true,
  "step": "cron_setup",
  "mode": "user_picked_${TARGET_KIND}",
  "action": "$CRON_ACTION",
  "added_id": "$ADDED_ID",
  "dedup_removed": $DEDUP_REMOVED,
  "channel_used": "$CHANNEL_ARG",
  "target": "$TARGET",
  "to_arg": "$TO_ARG",
  "agent_id": "$AGENT_ID",
  "message": "$( [ "$CRON_ACTION" = "recreated" ] && echo "已重建 cron (删旧建新)"; [ "$CRON_ACTION" = "created" ] && echo "已建 cron"; [ "$CRON_ACTION" = "unchanged" ] && echo "cron 已存在且无变化, 跳过"; [ "$CRON_ACTION" = "deduped" ] && echo "清理了 $DEDUP_REMOVED 条同名重复 cron, 保留 1 条")"
}
EOF
