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

# Configuration
BASE_URL = "https://dev-strategistai.galaxiq.ai"
WS_URL = "wss://dev-strategistai.galaxiq.ai"
# The tenant ID provided by the user
TENANT_ID = "org_d1e1c1ea-6c90-431f-9337-3375dcdfef5c"
# The tenant ID extracted from the WebSocket URL provided by the user
TENANT_ID_FROM_URL = "d1e1c1ea-6c90-431f-9337-3375dcdfef5c"

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

async def listen_to_ws(tenant_id, stop_event):
    url = f"{WS_URL}/ws/{tenant_id}/tickets"
    logger.info(f"Connecting to WebSocket: {url}")
    try:
        async with websockets.connect(url) as websocket:
            logger.info(f"Connected to WS for tenant: {tenant_id}")
            while not stop_event.is_set():
                try:
                    message = await asyncio.wait_for(websocket.recv(), timeout=1.0)
                    logger.info(f" [WS RECEIVED] for {tenant_id}: {message}")
                except asyncio.TimeoutError:
                    continue
    except Exception as e:
        logger.error(f"WS Error for {tenant_id}: {e}")

async def run_chat_and_ticket(tenant_id):
    thread_id = f"diag-{uuid.uuid4().hex[:8]}"
    user_name = "DiagnoseBot"
    
    async with httpx.AsyncClient(timeout=60.0) as client:
        # 1. Start a conversation
        logger.info(f"--- Starting conversation in thread {thread_id} for tenant {tenant_id} ---")
        
        chat_queries = [
            "Hello, I need help with my account.",
            "I am having trouble accessing the dashboard.",
            "Can you please create a support ticket for me? My email is test@example.com and phone is 1234567890. The issue is that I cannot see my analytics. Priority is High."
        ]
        
        for query in chat_queries:
            logger.info(f"User: {query}")
            response = await client.post(
                f"{BASE_URL}/chat",
                data={
                    "tenant_id": tenant_id,
                    "query": query,
                    "thread_id": thread_id,
                    "user_name": user_name,
                    "role": "user"
                }
            )
            
            if response.status_code != 200:
                logger.error(f"Chat failed: {response.text}")
                return None
            
            data = response.json()
            ai_text = data.get("response", "")
            logger.info(f"AI: {ai_text}")
            
            if "[Record: Ticket" in ai_text:
                logger.info("Ticket creation detected in AI response!")
        
        # 2. Check ticket list
        logger.info(f"--- Checking ticket list for tenant {tenant_id} ---")
        response = await client.get(f"{BASE_URL}/tickets?tenant_id={tenant_id}")
        if response.status_code == 200:
            tickets = response.json().get("tickets", [])
            logger.info(f"Found {len(tickets)} tickets in {tenant_id}")
            # Look for our ticket
            our_tickets = [t for t in tickets if t.get("thread_id") == thread_id]
            if our_tickets:
                logger.info(f"SUCCESS: Found our ticket in DB: {our_tickets[0].get('ticket_id')}")
            else:
                logger.warning(f"FAILURE: Ticket not found in DB for thread {thread_id} in tenant {tenant_id}")
        else:
            logger.error(f"Failed to fetch tickets: {response.text}")

async def main():
    stop_event = asyncio.Event()
    
    # We will listen on BOTH variations to see where the event lands
    # and we will trigger the chat with the user's provided tenant_id (org_...)
    
    ws_task1 = asyncio.create_task(listen_to_ws(TENANT_ID, stop_event))
    ws_task2 = asyncio.create_task(listen_to_ws(TENANT_ID_FROM_URL, stop_event))
    
    # Give WS time to connect
    await asyncio.sleep(2)
    
    try:
        # Run the test with the prefixed ID
        await run_chat_and_ticket(TENANT_ID)
        
        # Wait a bit for WS events
        await asyncio.sleep(5)
        
        # Now try running with the non-prefixed ID just to see what happens
        # await run_chat_and_ticket(TENANT_ID_FROM_URL)
        # await asyncio.sleep(5)
        
    finally:
        stop_event.set()
        await asyncio.gather(ws_task1, ws_task2, return_exceptions=True)

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