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 run_discovery():
    print("🔎 Discovery: Searching for Selections and Associate Mapping...")
    client = SuperOfficeClient()
    if not client.access_token:
        print("❌ Auth failed.")
        return

    # 1. Search for Selections
    print("\n📁 Searching for 'Roboplanet' Selections...")
    # Selections can be found via Archive or direct endpoint
    selections = client.search("Selection?$filter=name contains 'Roboplanet'")
    if selections:
        print(f"✅ Found {len(selections)} matching selections:")
        for sel in selections:
            sid = sel.get('SelectionId') or sel.get('selectionId')
            name = sel.get('Name') or sel.get('name')
            print(f"   - {name} (ID: {sid})")
    else:
        print("⚠️ No selections found with name 'Roboplanet'.")

    # 2. Get Associate Mapping via Archive Provider
    # This avoids the Associate/{id} 500 error
    print("\n👥 Fetching Associate-to-Group mapping via Archive...")
    # Provider 'associate' is standard
    endpoint = "Archive/dynamic?provider=associate&columns=associateId,name,groupIdx"
    try:
        mapping_data = client._get(endpoint)
        if mapping_data and isinstance(mapping_data, list):
            print(f"✅ Received {len(mapping_data)} associate records.")
            robo_user_ids = []
            for item in mapping_data:
                aid = item.get("associateId")
                name = item.get("name")
                gid = item.get("groupIdx")
                
                if gid == 52:
                    print(f"   - [ROBO] {name} (ID: {aid}, Group: {gid})")
                    robo_user_ids.append(aid)
                elif "Fottner" in str(name) or aid == 321:
                    print(f"   - [EXCLUDE] {name} (ID: {aid}, Group: {gid})")

            print(f"\n🚀 Identified {len(robo_user_ids)} Roboplanet Users.")
            if robo_user_ids:
                print(f"List of IDs: {robo_user_ids}")
        else:
            print("❌ Archive query returned no associate mapping.")
    except Exception as e:
        print(f"❌ Archive query failed: {e}")

if __name__ == "__main__":
    run_discovery()
