import httpx
import asyncio
import logging

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

async def test_auth():
    url = "http://localhost:5000/api/agent/chat"
    
    # 1. Test GUEST Mode (No Token)
    logger.info("--- TEST 1: GUEST MODE (No Token) ---")
    payload_guest = {
        "device_id": "device_guest_123",
        "user_query": "hello guest"
    }
    try:
        async with httpx.AsyncClient(timeout=10.0) as client:
            resp = await client.post(url, json=payload_guest)
            if resp.status_code == 200:
                data = resp.json()
                limit = data.get("limit_info", {}).get("limit")
                used = data.get("limit_info", {}).get("used")
                logger.info(f"✅ Guest Response Limit: {limit} (Expected 10)")
                if limit == 10:
                     logger.info("=> Logic Guest OK")
                else:
                     logger.error(f"=> Logic Guest FAILED (Limit is {limit})")
            else:
                logger.error(f"Request failed: {resp.text}")
    except Exception as e:
        logger.error(f"Error Test 1: {e}")

    # 2. Test USER Mode (With Token)
    logger.info("\n--- TEST 2: USER MODE (With Access Token) ---")
    token = "071w198x23ict4hs1i6bl889fit5p3f7"
    payload_user = {
        "device_id": "device_user_123", # device_id này sẽ bị ignore nếu token valid
        "user_query": "hello user"
    }
    headers = {
        "Authorization": f"Bearer {token}"
    }
    
    try:
        async with httpx.AsyncClient(timeout=20.0) as client:
            resp = await client.post(url, json=payload_user, headers=headers)
            if resp.status_code == 200:
                data = resp.json()
                limit = data.get("limit_info", {}).get("limit")
                used = data.get("limit_info", {}).get("used")
                logger.info(f"✅ User Response Limit: {limit} (Expected 100)")
                
                if limit == 100:
                     logger.info("=> Logic User OK (Prioritized Token over DeviceID)")
                elif limit == 10:
                     logger.warning("=> Logic User FAILED (Still Guest Mode). Token might be invalid or Canifa API unreachable.")
                else:
                     logger.info(f"=> Unexpected Limit: {limit}")
            elif resp.status_code == 429:
                logger.warning("Rate limit exceeded for this user/device.")
            else:
                logger.error(f"Request failed: {resp.status_code} - {resp.text}")

    except Exception as e:
        logger.error(f"Error Test 2: {e}")

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