#!/usr/bin/env bash
#
# inspect-mdirect.sh
#
# Fetches m.direct account data and the actual joined members for each
# room, then flags any group DMs that would trigger the findDM bug.
#
# Usage:
#   ./inspect-mdirect.sh <full_user_id> <access_token>
#
# Example:
#   ./inspect-mdirect.sh @alice:matrix.org syt_abc123...
#

set -euo pipefail

if [ $# -ne 2 ]; then
    echo "Usage: $0 <full_user_id> <access_token>"
    echo ""
    echo "  full_user_id  e.g. @alice:matrix.org"
    echo "  access_token  your session/access token"
    exit 1
fi

USER_ID="$1"
ACCESS_TOKEN="$2"

# Extract server domain from the user ID (@user:domain)
SERVER_DOMAIN="${USER_ID#*:}"
if [ -z "$SERVER_DOMAIN" ] || [ "$SERVER_DOMAIN" = "$USER_ID" ]; then
    echo "Error: could not extract server domain from user ID '${USER_ID}'." >&2
    echo "Expected format: @user:domain" >&2
    exit 1
fi

# Resolve actual homeserver URL via .well-known
echo "Resolving homeserver via .well-known for ${SERVER_DOMAIN}..."
HOMESERVER=""
WELL_KNOWN=$(curl -sf "https://${SERVER_DOMAIN}/.well-known/matrix/client" 2>/dev/null) || true
if [ -n "$WELL_KNOWN" ]; then
    HOMESERVER=$(echo "$WELL_KNOWN" | python3 -c '
import json, sys
data = json.load(sys.stdin)
hs = data.get("m.homeserver", {}).get("base_url", "")
print(hs.rstrip("/"))
')
fi
if [ -z "$HOMESERVER" ]; then
    HOMESERVER="https://${SERVER_DOMAIN}"
    echo "  .well-known not found, falling back to ${HOMESERVER}"
else
    echo "  Resolved to: ${HOMESERVER}"
fi

# URL-encode the user ID (@ and : need encoding)
ENCODED_USER_ID=$(printf '%s' "$USER_ID" | sed 's/@/%40/g; s/:/%3A/g')

URL="${HOMESERVER}/_matrix/client/v3/user/${ENCODED_USER_ID}/account_data/m.direct"

echo "Fetching m.direct from: ${URL}"
echo ""

RESPONSE=$(curl -sf -H "Authorization: Bearer ${ACCESS_TOKEN}" "$URL") || {
    echo "Error: failed to fetch m.direct. Check your homeserver URL, user ID, and access token." >&2
    exit 1
}

# Collect unique room IDs
ROOM_IDS=$(echo "$RESPONSE" | python3 -c '
import json, sys
data = json.load(sys.stdin)
seen = set()
for room_ids in data.values():
    for rid in room_ids:
        if rid not in seen:
            seen.add(rid)
            print(rid)
')

ROOM_COUNT=$(echo "$ROOM_IDS" | wc -l)
echo "Found ${ROOM_COUNT} direct rooms. Fetching joined members for each..."

# Fetch joined members for every room
declare -A ROOM_MEMBERS
for ROOM_ID in $ROOM_IDS; do
    ENCODED_ROOM_ID=$(printf '%s' "$ROOM_ID" | sed 's/!/%21/g; s/:/%3A/g')
    MEMBERS_URL="${HOMESERVER}/_matrix/client/v3/rooms/${ENCODED_ROOM_ID}/joined_members"
    MEMBERS_RESPONSE=$(curl -sf -H "Authorization: Bearer ${ACCESS_TOKEN}" "$MEMBERS_URL" 2>/dev/null) || MEMBERS_RESPONSE='{"joined":{}}'
    ROOM_MEMBERS["$ROOM_ID"]="$MEMBERS_RESPONSE"
done

# Print per-user summary
echo "$RESPONSE" | python3 -c '
import json, sys
data = json.load(sys.stdin)
if not data:
    print("m.direct is empty.")
    sys.exit(0)
print("")
print("=" * 70)
print("PER USER")
print("=" * 70)
for user_id, room_ids in sorted(data.items()):
    print(f"\n  {user_id}  ({len(room_ids)} room(s))")
    for rid in room_ids:
        print(f"    {rid}")
'

# Check every room: print m.direct target count + actual member count + verdict
echo ""
echo "======================================================================"
echo "CHECKING ACTUAL MEMBER COUNTS FOR ALL DIRECT ROOMS"
echo "======================================================================"

BUG_FOUND=0
for ROOM_ID in $ROOM_IDS; do
    MEMBERS_JSON="${ROOM_MEMBERS[$ROOM_ID]}"
    MEMBER_INFO=$(echo "$MEMBERS_JSON" | python3 -c '
import json, sys
data = json.load(sys.stdin)
joined = data.get("joined", {})
count = len(joined)
members = ", ".join(sorted(joined.keys()))
print(f"{count}|{members}")
')
    MEMBER_COUNT="${MEMBER_INFO%%|*}"
    MEMBER_LIST="${MEMBER_INFO#*|}"

    DM_TARGET_INFO=$(echo "$RESPONSE" | python3 -c "
import json, sys
data = json.load(sys.stdin)
rid = '$ROOM_ID'
targets = [u for u, rooms in data.items() if rid in rooms]
print(str(len(targets)) + '|' + ', '.join(targets))
")
    DM_TARGET_COUNT="${DM_TARGET_INFO%%|*}"
    DM_TARGET_USERS="${DM_TARGET_INFO#*|}"

    if [ "$MEMBER_COUNT" -gt 2 ] && [ "$DM_TARGET_COUNT" -eq 1 ]; then
        echo ""
        echo "  *** BUG TRIGGER: $ROOM_ID"
        echo "      m.direct target: $DM_TARGET_USERS"
        echo "        ^ Search for this user in Element X to reproduce the bug"
        echo "      Actual members:  $MEMBER_COUNT (this is really a group DM!)"
        echo "      Members: $MEMBER_LIST"
        BUG_FOUND=1
    elif [ "$MEMBER_COUNT" -gt 2 ]; then
        echo ""
        echo "  OK (group, multi-listed): $ROOM_ID"
        echo "      m.direct targets: $DM_TARGET_COUNT ($DM_TARGET_USERS)"
        echo "      Actual members:   $MEMBER_COUNT"
        echo "      Members: $MEMBER_LIST"
    else
        echo ""
        echo "  OK (true 1:1 DM): $ROOM_ID"
        echo "      m.direct targets: $DM_TARGET_COUNT ($DM_TARGET_USERS)"
        echo "      Actual members:   $MEMBER_COUNT"
        echo "      Members: $MEMBER_LIST"
    fi
done

echo ""
echo "======================================================================"
if [ "$BUG_FOUND" -eq 1 ]; then
    echo "RESULT: Bug confirmed! Rooms marked *** BUG TRIGGER above are group"
    echo "DMs that the Rust SDK would return as 1:1 DMs because they are listed"
    echo "under exactly 1 user in m.direct (dm_targets.len() == 1)."
else
    echo "RESULT: No bug-triggering rooms found in your m.direct data."
    echo "All group DMs are correctly listed under multiple users."
fi
echo "======================================================================"
