#!/bin/bash

# Debug script for Feishu App ID extraction

CONFIG_FILE="/home/ubuntu/openclaw-config/openclaw-qiangwu/openclaw.json"

echo "==================================="
echo "Feishu App ID Extraction Debug"
echo "==================================="
echo ""

echo "Step 1: Check if config file exists"
if [ -f "$CONFIG_FILE" ]; then
    echo "✓ File exists: $CONFIG_FILE"
else
    echo "✗ File not found: $CONFIG_FILE"
    exit 1
fi

echo ""
echo "Step 2: Test Python JSON parsing"
python3 - "$CONFIG_FILE" <<'PYEOF'
import json
import sys

config_file = sys.argv[1]

try:
    with open(config_file, 'r', encoding='utf-8') as f:
        data = json.load(f)
    print("✓ JSON parsed successfully")

    # Check structure
    channels = data.get('channels', {})
    print(f"  Has 'channels': {bool(channels)}")

    feishu = channels.get('feishu', {})
    print(f"  Has 'feishu': {bool(feishu)}")

    accounts = feishu.get('accounts', {})
    print(f"  Has 'accounts': {bool(accounts)}")
    print(f"  Account names: {list(accounts.keys())}")

    if accounts:
        for account_name, account_data in accounts.items():
            app_id = account_data.get('appId', '')
            print(f"  Account '{account_name}' -> appId: '{app_id}'")

except Exception as e:
    print(f"✗ Error: {e}")
    import traceback
    traceback.print_exc()
PYEOF

echo ""
echo "Step 3: Extract App ID only (stdout)"
RESULT=$(python3 - "$CONFIG_FILE" <<'PYEOF' 2>/dev/null
import json
import sys

config_file = sys.argv[1]

try:
    with open(config_file, 'r', encoding='utf-8') as f:
        data = json.load(f)
        channels = data.get('channels', {})
        feishu = channels.get('feishu', {})
        accounts = feishu.get('accounts', {})

        if accounts:
            for account_name, account_data in accounts.items():
                app_id = account_data.get('appId', '')
                if app_id:
                    print(app_id)
                    sys.exit(0)

        app_id = feishu.get('app-id', '')
        if app_id:
            print(app_id)
            sys.exit(0)

        print('-')
except Exception:
    print('-')
    sys.exit(1)
PYEOF
)

echo "Extracted App ID: '$RESULT'"

if [ "$RESULT" = "-" ]; then
    echo "✗ Failed to extract App ID"
    exit 1
else
    echo "✓ Success!"
fi

echo ""
echo "Step 4: Check run.sh version"
if grep -q "python3 - \"\$config_file\"" ./run.sh; then
    echo "✓ run.sh has been updated to new version"
else
    echo "✗ run.sh is still using old version"
    echo "  You need to: git pull origin feat/daily-stats-fix"
fi
