import sys
import os
import json

# Absolute path setup to avoid import errors
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 discover_associates_and_groups():
    print("🔎 Discovering Associates and Groups...")
    client = SuperOfficeClient()
    if not client.access_token:
        print("❌ Auth failed.")
        return

    # 1. Fetch User Groups
    print("\n👥 Fetching User Groups...")
    groups = client._get("MDOList/usergroup")
    
    robo_group_id = None
    
    if groups:
        for group in groups:
            name = group.get('Name')
            grp_id = group.get('Id')
            print(f"   - Group: {name} (ID: {grp_id})")
            if "Roboplanet" in name:
                robo_group_id = grp_id
    
    if robo_group_id:
        print(f"✅ Identified Roboplanet Group ID: {robo_group_id}")
    else:
        print("⚠️ Could not auto-identify Roboplanet group. Check the list above.")

    # 2. Check Candidate IDs directly
    print("\n👤 Checking specific Person IDs for Willi Fottner...")
    candidates = [6, 182552]
    
    for pid in candidates:
        try:
            p = client.get_person(pid)
            if p:
                fname = p.get('Firstname')
                lname = p.get('Lastname')
                is_assoc = p.get('IsAssociate')
                
                print(f"   👉 Person {pid}: {fname} {lname} (IsAssociate: {is_assoc})")
                
                if is_assoc:
                     assoc_obj = p.get("Associate")
                     if assoc_obj:
                         assoc_id = assoc_obj.get("AssociateId")
                         grp = assoc_obj.get("GroupIdx")
                         print(f"     ✅ IS ASSOCIATE! ID: {assoc_id}, Group: {grp}")
                         if "Fottner" in str(lname) or "Willi" in str(fname):
                             print(f"     🎯 TARGET IDENTIFIED: Willi Fottner is Associate ID {assoc_id}")
        except Exception as e:
            print(f"   ❌ Error checking Person {pid}: {e}")

    print("\n--- Done ---")

if __name__ == "__main__":
    discover_associates_and_groups()
