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_total_counts():
    print("📊 Verifying Global Account Counts...")
    client = SuperOfficeClient()
    if not client.access_token:
        print("❌ Auth failed.")
        return

    whitelist = settings.ROBOPLANET_WHITELIST
    
    # 1. Try to get MemberCount from the Selection 10960 directly
    print("\n📁 Checking Selection 10960 (Alle_Contacts_Roboplanet)...")
    try:
        sel_details = client._get("Selection/10960")
        if sel_details:
            # Note: MemberCount is often a property of the Selection entity
            count = sel_details.get("MemberCount")
            print(f"   🔹 Web-Interface-equivalent Count (MemberCount): {count}")
    except Exception as e:
        print(f"   ⚠️ Could not fetch Selection count property: {e}")

    # 2. Manual Aggregate Count via OData
    # We construct a filter for all our IDs and Shortnames
    # This might be too long for a URL, so we do it in smaller batches if needed
    print("\n📡 Calculating Netto Count for Whitelist (IDs + Names)...")
    
    # Divide whitelist into IDs and Names
    ids = [x for x in whitelist if isinstance(x, int)]
    names = [x for x in whitelist if isinstance(x, str)]
    
    # Construct OData filter string
    # example: (associateId eq 528 or associateId eq 485 or associateId eq 'RKAB')
    id_filters = [f"associateId eq {i}" for i in ids]
    name_filters = [f"associateId eq '{n}'" for n in names]
    full_filter = " or ".join(id_filters + name_filters)
    
    # We use $top=0 and $count=true to get JUST the number
    endpoint = f"Contact?$filter={full_filter}&$top=0&$count=true"
    
    try:
        # Note: If the URL is too long (> 2000 chars), this might fail.
        # But for ~60 entries it should be fine.
        resp = client._get(endpoint)
        total_api_count = resp.get("@odata.count")
        print(f"   🎯 API Calculated Count (Whitelist-Match): {total_api_count}")
        
        if total_api_count is not None:
            print(f"\n✅ PROOF: The API identifies {total_api_count} accounts for Roboplanet.")
            print("👉 Bitte vergleiche diese Zahl mit der Selektion 'Alle_Contacts_Roboplanet' im SuperOffice Web-Interface.")
        else:
            print("❌ API did not return a count property.")
            
    except Exception as e:
        print(f"❌ OData Aggregation failed: {e}")
        print("   The filter string might be too long for the API.")

if __name__ == "__main__":
    verify_total_counts()
