#!/bin/bash
set -e

echo "========================================"
echo "君鸿卡管系统部署诊断脚本"
echo "========================================"
echo ""

cd /opt/junhong_cmp

echo "1. 检查镜像信息"
echo "----------------------------------------"
docker images | grep junhong/cmp-fiber-api
echo ""

echo "2. 检查容器状态"
echo "----------------------------------------"
docker compose -f docker-compose.prod.yml ps
echo ""

echo "3. 查看 API 容器详细健康状态"
echo "----------------------------------------"
docker inspect junhong-cmp-api --format='{{json .State.Health}}' | jq .
echo ""

echo "4. 查看 API 容器启动日志（最近 50 行）"
echo "----------------------------------------"
docker compose -f docker-compose.prod.yml logs api --tail=50
echo ""

echo "5. 手动测试健康检查（容器内）"
echo "----------------------------------------"
echo "测试 IPv4 (127.0.0.1):"
docker exec junhong-cmp-api wget --no-verbose --tries=1 --spider http://127.0.0.1:3000/health && echo "✅ 成功" || echo "❌ 失败"
echo ""
echo "测试 localhost:"
docker exec junhong-cmp-api wget --no-verbose --tries=1 --spider http://localhost:3000/health && echo "✅ 成功" || echo "❌ 失败"
echo ""

echo "6. 从宿主机测试健康检查"
echo "----------------------------------------"
curl -s http://localhost:3000/health | jq .
echo ""

echo "7. 检查端口监听情况（容器内）"
echo "----------------------------------------"
docker exec junhong-cmp-api netstat -tlnp 2>/dev/null || docker exec junhong-cmp-api ss -tlnp
echo ""

echo "8. 查看环境变量"
echo "----------------------------------------"
docker exec junhong-cmp-api env | grep -E "DB_|CONFIG_ENV"
echo ""

echo "9. 检查配置文件"
echo "----------------------------------------"
docker exec junhong-cmp-api cat /app/configs/config.yaml | grep -A 3 "server:"
echo ""

echo "========================================"
echo "诊断完成"
echo "========================================"
