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

def inspect_group():
    print("🔎 Inspecting Group 52 (Roboplanet)...")
    client = SuperOfficeClient()
    if not client.access_token:
        print("❌ Auth failed.")
        return

    # 1. Find Users in Group 52
    print("\n👥 Finding Associates in Group 52...")
    associates = client._get("MDOList/associate")
    
    robo_associates = []
    if associates:
        for assoc in associates:
            # Note: MDOList returns flat items. 
            # We might need to fetch details or check 'GroupIdx' if present in ExtraInfo
            # Let's check keys first
            # print(assoc.keys())
            
            # The 'GroupIdx' is usually in 'ExtraInfo' or needs detail fetch
            # But earlier discovery showed 'GroupIdx' directly? No, I inferred it.
            # Let's fetch details for a few to be sure.
            assoc_id = assoc.get('Id')
            
            # Optimization: Only check first 50 to avoid spam, or check by Name if we know one
            # Better: Use OData to filter associates by group? 
            # "Associate?$filter=groupIdx eq 52" -> Let's try this first!
            pass

    # Efficient OData Search for Associates in Group 52
    users_in_group = client.search("Associate?$filter=groupIdx eq 52")
    
    if users_in_group:
        print(f"✅ Found {len(users_in_group)} Associates in Group 52:")
        for u in users_in_group:
            uid = u.get('associateId') or u.get('AssociateId')
            name = u.get('name') or u.get('Name') or u.get('fullName')
            print(f"   - {name} (ID: {uid})")
            robo_associates.append(uid)
    else:
        print("⚠️ No Associates found in Group 52 via OData.")
        print("   Trying manual scan of MDOList (slower)...")
        # Fallback loop
        if associates:
            count = 0
            for assoc in associates:
                aid = assoc.get('Id')
                det = client._get(f"Associate/{aid}")
                if det and det.get('GroupIdx') == 52:
                    print(f"   - {det.get('Name')} (ID: {aid}) [via Detail]")
                    robo_associates.append(aid)
                    count += 1
                if count > 5: 
                    print("   ... (stopping scan)")
                    break

    if not robo_associates:
        print("❌ CRITICAL: Group 52 seems empty! Filter logic will block everything.")
        return

    # 2. Check a Contact owned by one of these users
    test_user_id = robo_associates[0]
    print(f"\n🏢 Checking a Contact owned by User {test_user_id}...")
    
    contacts = client.search(f"Contact?$filter=associateId eq {test_user_id}&$top=1&$select=ContactId,Name,Associate/GroupIdx")
    
    if contacts:
        c = contacts[0]
        cid = c.get('contactId') or c.get('ContactId')
        cname = c.get('name') or c.get('Name')
        # Check nested Associate GroupIdx if returned, or fetch detail
        print(f"   found: {cname} (ID: {cid})")
        
        # Double Check with full Get
        full_c = client.get_contact(cid)
        assoc_grp = full_c.get('Associate', {}).get('GroupIdx')
        print(f"   👉 Contact Associate GroupIdx: {assoc_grp}")
        
        if assoc_grp == 52:
            print("✅ VERIFIED: Filter logic 'GroupIdx == 52' will work.")
        else:
            print(f"❌ MISMATCH: Contact GroupIdx is {assoc_grp}, expected 52.")
    else:
        print("⚠️ User has no contacts. Cannot verify contact group mapping.")

if __name__ == "__main__":
    inspect_group()
