#!/usr/bin/env bash

# 偶合 OppHub · 通道管理（v2.0.0）
# chinabot 12:54 全重写：零 read -p
# 用法：
#   opphub channel list --json
#   opphub channel add --type feishu --id X --json
#   opphub channel setup --auto --json
#   opphub channel rm --id X --json

_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"

set -e

ACTION=""
TYPE_=""
ID_=""
AUTO_MODE=false
JSON_OUT=true

while [ $# -gt 0 ]; do
  case "$1" in
    list|add|bind|rm|delete|setup|list-installable|--type|--id|--auto|--json|--human|--help|-h|help) ;;
    *) json_error channel_args BAD_REQUEST "未知参数: $1" ;;
  esac
  case "$1" in
    list|add|bind|rm|delete|setup|list-installable|help)
      ACTION="$1"; shift ;;
    --type) TYPE_="$2"; shift 2 ;;
    --id) ID_="$2"; shift 2 ;;
    --auto) AUTO_MODE=true; shift ;;
    --json) JSON_OUT=true; shift ;;
    --human) JSON_OUT=false; shift ;;
    --help|-h)
      cat <<'USAGE'
opphub channel — 通道管理（v2.0.0）

用法：
  opphub channel list --json
  opphub channel add --type feishu --id <account> --json
  opphub channel rm --id <account> --json
  opphub channel setup --auto --json   # 自动装+建 cron
  opphub channel list-installable --json
USAGE
      exit 0 ;;
  esac
done

ACTION="${ACTION:-list}"
require_bot_mode

case "$ACTION" in
  list)
    api_call GET "/api/channel/list" "" channelId channelType
    if [ "$RESP_OK" = "true" ]; then
      # 把整段响应原样输出（含数组）
      echo "$CURL_LAST_RESPONSE"
    else
      json_error channel_list "$RESP_ERR_CODE" "$RESP_ERR_MSG"
    fi
    ;;

  add|bind)
    if [ -z "$TYPE_" ]; then
      # v2.2.0: 缺 --type 时给完整 supported 列表（问服务端，避免硬编码过期）
      api_call GET "/api/channel/list" "" "" "" 2>/dev/null || true
      json_error channel_args BAD_REQUEST "缺少 --type (feishu|weixin|wecom|dingtalk|qqbot|sms|email|... 30 个支持)"
    fi
    if [ -z "$ID_" ]; then
      json_error channel_args BAD_REQUEST "缺少 --id <account>"
    fi
    api_call POST "/api/channel/bind" "{\"channelType\":\"$TYPE_\",\"channelId\":\"$ID_\"}"
    if [ "$RESP_OK" = "true" ]; then
      echo "{\"ok\":true,\"step\":\"channel_added\",\"type\":\"$TYPE_\",\"id\":\"$ID_\"}"
    else
      # v2.2.0: invalid_channel_type 错误响应带 supported 字段 → 给前端完整列表
      if [ "$RESP_ERR_CODE" = "BAD_REQUEST" ] && echo "$CURL_LAST_RESPONSE" | grep -q "supported"; then
        SUPPORTED=$(echo "$CURL_LAST_RESPONSE" | python3 -c "import sys,json; d=json.load(sys.stdin); print(','.join(d.get('supported',[])))" 2>/dev/null || echo "")
        if [ -n "$SUPPORTED" ]; then
          json_error channel_add "$RESP_ERR_CODE" "$RESP_ERR_MSG (支持: $SUPPORTED)"
        fi
      fi
      json_error channel_add "$RESP_ERR_CODE" "$RESP_ERR_MSG"
    fi
    ;;

  rm|delete)
    [ -z "$ID_" ] && json_error channel_args BAD_REQUEST "缺少 --id"
    api_call DELETE "/api/channel/$ID_" ""
    [ "$RESP_OK" = "true" ] && \
      echo "{\"ok\":true,\"step\":\"channel_removed\",\"id\":\"$ID_\"}" || \
      json_error channel_rm "$RESP_ERR_CODE" "$RESP_ERR_MSG"
    ;;

  list-installable)
    source "$SCRIPT_DIR/../lib/opphub-cron.sh" 2>/dev/null || true
    opphub_cron_list_installable_channels
    ;;

  setup)
    if [ "$AUTO_MODE" = "true" ]; then
      # v2.8.0 老板 18:08 拍: 不再硬装默认通道, 调 cron-setup 按用户 OPPHUB 实际绑定通道
      exec "$SCRIPT_DIR/opphub-cron-setup" --auto --json
    else
      # setup 不带 --auto：只检查 + 给指引
      exec "$SCRIPT_DIR/opphub-cron-setup" --json
    fi
    ;;
esac
