import sys
import os
import json

# Absolute path setup
current_dir = os.path.dirname(os.path.abspath(__file__))
connector_dir = os.path.abspath(os.path.join(current_dir, '..'))
sys.path.insert(0, connector_dir)

from superoffice_client import SuperOfficeClient
from config import settings

def verify():
    selection_id = 10960
    print(f"🔎 Verifying members of Selection {selection_id}...")
    client = SuperOfficeClient()
    if not client.access_token:
        print("❌ Auth failed.")
        return

    # Use the Selection/ID/ContactMembers endpoint which is part of the REST API
    # We ask for a few members and their Associate info
    endpoint = f"Selection/{selection_id}/ContactMembers?$top=50&$select=ContactId,Name,AssociateId"
    
    print(f"📡 Querying: {endpoint}")
    try:
        resp = client._get(endpoint)
        # OData returns 'value'
        members = resp.get('value', [])
        
        if not members:
            print("⚠️ No members found via REST. Trying alternative Archive call...")
            # If REST fails, we might have to use a different approach
            return

        print(f"✅ Found {len(members)} members. Inspecting owners...")
        
        whitelist = settings.ROBOPLANET_WHITELIST
        owners_found = {}
        
        for m in members:
            cid = m.get('ContactId')
            cname = m.get('Name')
            # The AssociateId might be named differently in the response
            aid = m.get('AssociateId')
            
            if aid:
                is_robo = aid in whitelist or str(aid).upper() in whitelist
                status = "✅ ROBO" if is_robo else "❌ STRANGER"
                owners_found[aid] = (status, aid)
                # print(f"   - Contact {cid} ({cname}): Owner {aid} [{status}]")

        print("\n📊 Summary of Owners in Selection:")
        for aid, (status, val) in owners_found.items():
            print(f"   {status}: Associate {aid}")

        if any("STRANGER" in s for s, v in owners_found.values()):
             print("\n⚠️ ALERT: Found owners in the selection who are NOT in our whitelist.")
             print("This explains the delta. Please check if these IDs should be added.")
        else:
             print("\n✅ All sampled members belong to whitelist users.")

    except Exception as e:
        print(f"❌ Error: {e}")

if __name__ == "__main__":
    verify()
