#!/usr/bin/env python3
"""
Simple test script to verify TeleBot's full functionality
by testing the API calls the bot would make.
"""

import requests
import json
import uuid
import sys

# API Configuration
API_BASE = "http://localhost:5000/api"
BOT_ID = str(uuid.uuid4())
IDENTITY_REF = f"bot-test-{uuid.uuid4().hex[:8]}"

def test_bot_registration():
    """Test bot registration"""
    print("🤖 Testing Bot Registration...")
    
    response = requests.post(f"{API_BASE}/bots/register", json={
        "name": "TestBot",
        "description": "Test bot for functionality verification"
    })
    
    if response.status_code == 200:
        data = response.json()
        print(f"✅ Bot registered: {data.get('botId', 'Unknown ID')}")
        return data.get('botId')
    else:
        print(f"❌ Bot registration failed: {response.status_code} - {response.text}")
        return None

def test_catalog_browsing():
    """Test catalog browsing (what happens when user clicks 'Browse Products')"""
    print("\n📱 Testing Catalog Browsing...")
    
    # Get categories
    response = requests.get(f"{API_BASE}/catalog/categories")
    if response.status_code == 200:
        categories = response.json()
        print(f"✅ Found {len(categories)} categories:")
        for cat in categories[:3]:  # Show first 3
            print(f"   • {cat['name']}")
    else:
        print(f"❌ Categories failed: {response.status_code}")
        return False
    
    # Get products
    response = requests.get(f"{API_BASE}/catalog/products")
    if response.status_code == 200:
        products = response.json()
        print(f"✅ Found {len(products)} products:")
        for prod in products[:3]:  # Show first 3
            print(f"   • {prod['name']} - £{prod['price']}")
        return products
    else:
        print(f"❌ Products failed: {response.status_code}")
        return False

def test_order_creation(products):
    """Test order creation (what happens when user confirms checkout)"""
    print("\n🛒 Testing Order Creation...")
    
    if not products:
        print("❌ No products available for order test")
        return False
        
    # Create a test order with first product
    test_product = products[0]
    order_data = {
        "identityReference": IDENTITY_REF,
        "items": [
            {
                "productId": test_product["id"],
                "quantity": 2
            }
        ],
        "shippingName": "Test Customer",
        "shippingAddress": "123 Test Street",
        "shippingCity": "London",
        "shippingPostcode": "SW1A 1AA",
        "shippingCountry": "UK"
    }
    
    response = requests.post(f"{API_BASE}/orders", json=order_data)
    if response.status_code == 201:
        order = response.json()
        print(f"✅ Order created: {order['id']}")
        print(f"   Status: {order['status']}")
        print(f"   Total: £{order['totalAmount']}")
        return order
    else:
        print(f"❌ Order creation failed: {response.status_code}")
        print(f"   Response: {response.text}")
        return False

def test_order_retrieval():
    """Test order retrieval (what happens when user clicks 'My Orders')"""
    print("\n📋 Testing Order Retrieval...")
    
    response = requests.get(f"{API_BASE}/orders/by-identity/{IDENTITY_REF}")
    if response.status_code == 200:
        orders = response.json()
        print(f"✅ Found {len(orders)} orders for identity {IDENTITY_REF}")
        for order in orders:
            print(f"   • Order {order['id'][:8]}... - Status: {order['status']} - £{order['totalAmount']}")
        return True
    else:
        print(f"❌ Order retrieval failed: {response.status_code}")
        return False

def test_payment_creation(order):
    """Test payment creation (what happens when user selects crypto payment)"""
    print("\n💰 Testing Payment Creation...")
    
    if not order:
        print("❌ No order available for payment test")
        return False
    
    payment_data = {
        "currency": "BTC",
        "amount": order["totalAmount"]
    }
    
    response = requests.post(f"{API_BASE}/orders/{order['id']}/payments", json=payment_data)
    if response.status_code == 201:
        payment = response.json()
        print(f"✅ Payment created: {payment['id']}")
        print(f"   Currency: {payment['currency']}")
        print(f"   Amount: {payment['amount']}")
        print(f"   Status: {payment['status']}")
        return payment
    else:
        print(f"❌ Payment creation failed: {response.status_code}")
        print(f"   Response: {response.text}")
        return False

def main():
    print("🧪 TeleBot Full Functionality Test")
    print("=" * 50)
    
    # Test 1: Bot Registration
    bot_id = test_bot_registration()
    if not bot_id:
        print("\n❌ Test failed at bot registration")
        sys.exit(1)
    
    # Test 2: Catalog Browsing
    products = test_catalog_browsing()
    if not products:
        print("\n❌ Test failed at catalog browsing")
        sys.exit(1)
    
    # Test 3: Order Creation
    order = test_order_creation(products)
    if not order:
        print("\n❌ Test failed at order creation")
        sys.exit(1)
    
    # Test 4: Order Retrieval
    if not test_order_retrieval():
        print("\n❌ Test failed at order retrieval")
        sys.exit(1)
    
    # Test 5: Payment Creation
    payment = test_payment_creation(order)
    if not payment:
        print("\n❌ Test failed at payment creation")
        sys.exit(1)
    
    print("\n🎉 All tests passed! TeleBot functionality verified!")
    print(f"   • Bot can register")
    print(f"   • Bot can browse {len(products)} products")
    print(f"   • Bot can create orders")
    print(f"   • Bot can retrieve orders")
    print(f"   • Bot can create crypto payments")

if __name__ == "__main__":
    main()