import asyncio
import httpx
import uuid
import json
import logging
import websockets

# Configuration
BASE_URL = "https://dev-strategistai.galaxiq.ai"
WS_URL = "wss://dev-strategistai.galaxiq.ai"
# The "correct" tenant ID with prefix
TENANT_ID_WITH_ORG = "org_d1e1c1ea-6c90-431f-9337-3375dcdfef5c"
# The tenant ID without prefix (often used by frontend or in URLs)
TENANT_ID_NO_ORG = "d1e1c1ea-6c90-431f-9337-3375dcdfef5c"

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger("reproduce_issue")

async def listen_to_ws(tenant_id, name, results):
    url = f"{WS_URL}/ws/{tenant_id}/tickets"
    logger.info(f" [{name}] Connecting to WebSocket: {url}")
    try:
        async with websockets.connect(url) as websocket:
            logger.info(f" [{name}] Connected.")
            while True:
                try:
                    message = await asyncio.wait_for(websocket.recv(), timeout=1.0)
                    logger.info(f" !!! [WS RECEIVED] on {name} ({tenant_id}): {message}")
                    results[name].append(message)
                except asyncio.TimeoutError:
                    continue
                except Exception as e:
                    logger.error(f" [{name}] WS Recv Error: {e}")
                    break
    except Exception as e:
        logger.error(f" [{name}] WS Connection Error: {e}")

async def run_test():
    results = {"WITH_ORG": [], "NO_ORG": []}
    
    # 1. Start listeners for BOTH variations
    ws_task1 = asyncio.create_task(listen_to_ws(TENANT_ID_WITH_ORG, "WITH_ORG", results))
    ws_task2 = asyncio.create_task(listen_to_ws(TENANT_ID_NO_ORG, "NO_ORG", results))
    
    await asyncio.sleep(2) # Wait for connections
    
    # 2. Trigger a ticket creation using the WITH_ORG tenant ID
    thread_id = f"repro-{uuid.uuid4().hex[:8]}"
    logger.info(f"--- Triggering ticket creation for {TENANT_ID_WITH_ORG} (Thread: {thread_id}) ---")
    
    async with httpx.AsyncClient(timeout=60.0) as client:
        # We'll use a direct message that forces a ticket
        query = f"Please create a support ticket for 'Reproduction Test'. Details: This is a test to see which WS channel receives the event. Email: test@example.com, Phone: 12345, Priority: High. Thread ID is {thread_id}."
        
        response = await client.post(
            f"{BASE_URL}/chat",
            data={
                "tenant_id": TENANT_ID_WITH_ORG,
                "query": query,
                "thread_id": thread_id,
                "user_name": "ReproBot",
                "role": "user"
            }
        )
        
        logger.info(f"Chat Response: {response.status_code}")
        if response.status_code == 200:
            logger.info(f"AI Response: {response.json().get('response')}")
        else:
            logger.error(f"Chat failed: {response.text}")
            
    # 3. Wait for events
    logger.info("Waiting 10 seconds for events...")
    await asyncio.sleep(10)
    
    # 4. Analysis
    logger.info("--- Test Results Analysis ---")
    if results["WITH_ORG"]:
        logger.info("SUCCESS: WS with 'org_' prefix received the event.")
    else:
        logger.warning("FAILURE: WS with 'org_' prefix DID NOT receive the event.")
        
    if results["NO_ORG"]:
        logger.info("NOTE: WS WITHOUT 'org_' prefix received the event. (This happens if you connect like Postman does)")
    else:
        logger.info("NOTE: WS WITHOUT 'org_' prefix DID NOT receive anything.")

    # Clean up
    ws_task1.cancel()
    ws_task2.cancel()

if __name__ == "__main__":
    asyncio.run(run_test())
