#!/bin/bash
# ═══════════════════════════════════════════════════════════
# 光湖语言系统 · 模块注册脚本
# 服务器上任一模块启动时调用 · 自动写入注册文件
#
# 用法:
#   module-register.sh --server GZ006 --func GTW --name "Gatekeeper" --port 8922
#   module-register.sh --stop GZ006-GTW-01
# ═══════════════════════════════════════════════════════════

REGISTRY_DIR="/opt/zhuyuan/registry/modules.d"
mkdir -p "$REGISTRY_DIR"

# ── 停止模式 ──
if [ "$1" = "--stop" ]; then
    CODE="$2"
    if [ -z "$CODE" ]; then
        echo "用法: $0 --stop {CODE}" >&2
        exit 1
    fi
    REG_FILE="$REGISTRY_DIR/MOD-${CODE}.json"
    if [ -f "$REG_FILE" ]; then
        python3 -c "
import json, sys
try:
    with open('$REG_FILE', 'r') as f:
        data = json.load(f)
    data['status'] = 'stopped'
    data['stopped_at'] = '$(date -u +%Y-%m-%dT%H:%M:%SZ)'
    with open('$REG_FILE', 'w') as f:
        json.dump(data, f, indent=2)
    print(f'⊢ 模块 {data[\"code\"]} 已标记为已停止')
except Exception as e:
    print(f'⚠ 更新注册文件失败: {e}', file=sys.stderr)
"
    fi
    exit 0
fi

# ── 注册模式 ──
SERVER=""
FUNC=""
NAME=""
PORT=""
PROTOCOL="tcp"
DESCRIPTION=""
PID="$$"

while [ $# -gt 0 ]; do
    case "$1" in
        --server) SERVER="$2"; shift 2 ;;
        --func)   FUNC="$2"; shift 2 ;;
        --name)   NAME="$2"; shift 2 ;;
        --port)   PORT="$2"; shift 2 ;;
        --protocol) PROTOCOL="$2"; shift 2 ;;
        --description) DESCRIPTION="$2"; shift 2 ;;
        --pid)    PID="$2"; shift 2 ;;
        *) shift ;;
    esac
done

if [ -z "$SERVER" ] || [ -z "$FUNC" ] || [ -z "$NAME" ]; then
    echo "❌ 缺少必要参数: --server --func --name" >&2
    exit 1
fi

# 计算序号（同一服务器+功能下，取最大序号+1）
SEQ=1
for f in "$REGISTRY_DIR"/MOD-${SERVER}-${FUNC}-*.json; do
    if [ -f "$f" ]; then
        existing_seq=$(basename "$f" .json | grep -oE '[0-9]+$')
        if [ -n "$existing_seq" ] && [ "$existing_seq" -ge "$SEQ" ]; then
            SEQ=$((existing_seq + 1))
        fi
    fi
done

# 格式化序号为两位
SEQ_FMT=$(printf "%02d" "$SEQ")
CODE="${SERVER}-${FUNC}-${SEQ_FMT}"
REG_FILE="$REGISTRY_DIR/MOD-${CODE}.json"
TIMESTAMP=$(date -u +%Y-%m-%dT%H:%M:%SZ)

python3 -c "
import json
data = {
    'code': '${CODE}',
    'server': '${SERVER}',
    'function': '${FUNC}',
    'name': '${NAME}',
    'port': ${PORT:-0},
    'protocol': '${PROTOCOL}',
    'description': '${DESCRIPTION}',
    'pid': ${PID},
    'started_at': '${TIMESTAMP}',
    'registered_at': '${TIMESTAMP}',
    'status': 'running'
}
with open('${REG_FILE}', 'w') as f:
    json.dump(data, f, indent=2, ensure_ascii=False)
print(f'✅ 模块已注册: {data[\"code\"]}')
print(f'   名称: ${NAME}')
print(f'   文件: MOD-${CODE}.json')
" 2>/dev/null || {
    # Python3 不可用时的降级方案（纯 shell 写 JSON）
    cat > "$REG_FILE" << JSONEOF
{
  "code": "${CODE}",
  "server": "${SERVER}",
  "function": "${FUNC}",
  "name": "${NAME}",
  "port": ${PORT:-0},
  "protocol": "${PROTOCOL}",
  "description": "${DESCRIPTION}",
  "pid": ${PID},
  "started_at": "${TIMESTAMP}",
  "registered_at": "${TIMESTAMP}",
  "status": "running"
}
JSONEOF
    echo "✅ 模块已注册: ${CODE}"
}
