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 run_precise_check():
    print("📊 Precise Count Verification: API vs. Whitelist...")
    client = SuperOfficeClient()
    if not client.access_token:
        print("❌ Auth failed.")
        return

    whitelist = settings.ROBOPLANET_WHITELIST
    ids_in_whitelist = [x for x in whitelist if isinstance(x, int)]
    
    # 1. Individual Counts for our Whitelist IDs
    print(f"\n🔢 Counting accounts for the {len(ids_in_whitelist)} IDs in whitelist...")
    total_whitelist_count = 0
    for aid in ids_in_whitelist:
        endpoint = f"Contact?$filter=associateId eq {aid}&$top=0&$count=true"
        try:
            resp = client._get(endpoint)
            count = resp.get('@odata.count') or 0
            if count > 0:
                # print(f"   - ID {aid}: {count}")
                total_whitelist_count += count
        except:
            pass
    
    print(f"✅ Total accounts owned by Whitelist IDs: {total_whitelist_count}")

    # 2. Check for "Strangers" in the Selection 10960
    # We want to find who else is in that selection
    print(f"\n🕵️ Looking for Owners in Selection 10960 who are NOT in our whitelist...")
    
    # We use Archive/dynamic to group members by AssociateId
    # This is the most efficient way to see all owners in the selection
    endpoint = "Archive/dynamic?provider=selectionmember&columns=contact/associateId,contact/associate/name&criteria=selectionId=10960&$top=1000"
    
    try:
        members = client._get(endpoint)
        if members and isinstance(members, list):
            owners_in_selection = {}
            for m in members:
                aid = m.get("contact/associateId")
                aname = m.get("contact/associate/name")
                if aid:
                    owners_in_selection[aid] = aname
            
            print(f"Found {len(owners_in_selection)} distinct owners in the first 1000 members of selection.")
            for aid, name in owners_in_selection.items():
                if aid not in whitelist and name not in whitelist:
                    print(f"   ⚠️ OWNER NOT IN WHITELIST: {name} (ID: {aid})")
        else:
            print("⚠️ Could not group selection members by owner via API.")
            
    except Exception as e:
        print(f"⚠️ Archive grouping failed: {e}")

    print(f"\n🏁 Target from UI: 17014")
    print(f"🏁 Whitelist sum: {total_whitelist_count}")
    delta = 17014 - total_whitelist_count
    print(f"🏁 Delta: {delta}")

if __name__ == "__main__":
    run_precise_check()
