#!/usr/bin/env python3
"""Verify GHL/Qdrant memory status."""
import urllib.request
import json
import ssl
import sys
sys.path.insert(0, '/mnt/e/genesis-system/core')

try:
    from secrets_loader import get_qdrant_config
    config = get_qdrant_config()
    QDRANT_URL = config.url
    API_KEY = config.api_key
except ImportError:
    print("[X] secrets_loader not available")
    sys.exit(1)

if not config.is_configured:
    print("[X] Qdrant not configured")
    sys.exit(1)

def make_request(endpoint, method="GET", data=None):
    url = f"{QDRANT_URL}/{endpoint}"
    headers = {
        "api-key": API_KEY,
        "Content-Type": "application/json"
    }

    # Create unverified context to avoid SSL cert issues if any
    ctx = ssl.create_default_context()
    ctx.check_hostname = False
    ctx.verify_mode = ssl.CERT_NONE

    req = urllib.request.Request(url, headers=headers, method=method)
    if data:
        req.data = json.dumps(data).encode('utf-8')

    try:
        with urllib.request.urlopen(req, context=ctx) as response:
            return json.loads(response.read().decode('utf-8'))
    except Exception as e:
        print(f"Error accessing {endpoint}: {e}")
        return None

def verify_ghl_memory():
    print("--- Verifying Shared Memory (Qdrant) ---")

    # 1. List Collections
    collections_data = make_request("collections")
    if not collections_data:
        print("Failed to list collections.")
        return

    collections = [c['name'] for c in collections_data.get('result', {}).get('collections', [])]
    print(f"Collections found: {collections}")

    # 2. Search for GHL in each collection
    for col in collections:
        print(f"\nSearching collection: {col}...")

        # Scroll through points to find recent entries
        search_data = make_request(f"collections/{col}/points/scroll", "POST", {"limit": 10, "with_payload": True})

        if search_data and 'result' in search_data:
            points = search_data['result'].get('points', [])
            ghl_count = 0
            for p in points:
                payload = p.get('payload', {})
                text_content = str(payload)
                if "GHL" in text_content or "GoHighLevel" in text_content:
                    ghl_count += 1
                    print(f"  [MATCH] Found GHL reference: {text_content[:100]}...")

            if ghl_count == 0:
                print("  No direct GHL references in top 10 recent points.")
        else:
            print("  No data returned.")

if __name__ == "__main__":
    verify_ghl_memory()
