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 find_latest_match():
    print("🔎 Searching for the youngest account assigned to a Roboplanet user...")
    client = SuperOfficeClient()
    if not client.access_token:
        print("❌ Auth failed.")
        return

    whitelist = settings.ROBOPLANET_WHITELIST
    print(f"📋 Whitelist contains {len(whitelist)} entries (IDs + Names).")

    # 1. Fetch more contacts to find a match
    limit = 1000
    endpoint = f"Contact?$orderby=contactId desc&$top={limit}&$select=contactId,name,associateId"
    
    print(f"📡 Fetching latest {limit} contacts (this may take a few seconds)...")
    try:
        contacts = client.search(endpoint)
        if not contacts:
            print("❌ No contacts returned from API.")
            return

        print(f"✅ Received {len(contacts)} contacts. Checking against whitelist...")
        
        found = False
        for i, c in enumerate(contacts):
            if i > 0 and i % 100 == 0:
                print(f"   ... checked {i} records ...")
            
            cid = c.get('contactId') or c.get('ContactId')
            cname = c.get('name') or c.get('Name')
            
            # Extract associate identifier (might be ID or Name)
            raw_aid = c.get('associateId') or c.get('AssociateId')
            
            is_match = False
            if raw_aid:
                # 1. Try as String (Name)
                val_str = str(raw_aid).upper().strip()
                if val_str in whitelist:
                    is_match = True
                else:
                    # 2. Try as Int (ID)
                    try:
                        if int(raw_aid) in whitelist:
                            is_match = True
                    except (ValueError, TypeError):
                        pass

            if is_match:
                print("\n🎯 FOUND YOUNGEST ROBOPLANET ACCOUNT:")
                print(f"   - Company Name: {cname}")
                print(f"   - Contact ID:   {cid}")
                print(f"   - Responsible Identifier: {raw_aid}")
                print(f"   - Link: https://online3.superoffice.com/Cust26720/default.aspx?contact?contact_id={cid}")
                found = True
                break
        
        if not found:
            print(f"\n⚠️ No match found in the last {limit} contacts.")
            print("   This confirms that recent activity is from non-whitelist users.")

    except Exception as e:
        print(f"❌ Error: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    find_latest_match()
