import requests
import sys
import json
from datetime import datetime

class LuxeAuraAPITester:
    def __init__(self, base_url="https://accessory-convert.preview.emergentagent.com"):
        self.base_url = base_url
        self.api_url = f"{base_url}/api"
        self.tests_run = 0
        self.tests_passed = 0
        self.cart_id = None

    def run_test(self, name, method, endpoint, expected_status, data=None, params=None):
        """Run a single API test"""
        url = f"{self.api_url}/{endpoint}"
        headers = {'Content-Type': 'application/json'}

        self.tests_run += 1
        print(f"\n🔍 Testing {name}...")
        print(f"   URL: {url}")
        
        try:
            if method == 'GET':
                response = requests.get(url, headers=headers, params=params)
            elif method == 'POST':
                response = requests.post(url, json=data, headers=headers)
            elif method == 'PUT':
                response = requests.put(url, json=data, headers=headers, params=params)
            elif method == 'DELETE':
                response = requests.delete(url, headers=headers)

            success = response.status_code == expected_status
            if success:
                self.tests_passed += 1
                print(f"✅ Passed - Status: {response.status_code}")
                try:
                    response_data = response.json()
                    print(f"   Response: {json.dumps(response_data, indent=2)[:200]}...")
                except:
                    print(f"   Response: {response.text[:200]}...")
            else:
                print(f"❌ Failed - Expected {expected_status}, got {response.status_code}")
                print(f"   Response: {response.text[:200]}...")

            return success, response.json() if response.text else {}

        except Exception as e:
            print(f"❌ Failed - Error: {str(e)}")
            return False, {}

    def test_api_root(self):
        """Test API root endpoint"""
        return self.run_test("API Root", "GET", "", 200)

    def test_get_products(self):
        """Test get all products"""
        return self.run_test("Get All Products", "GET", "products", 200)

    def test_get_new_arrivals(self):
        """Test get new arrivals"""
        return self.run_test("Get New Arrivals", "GET", "products/new-arrivals/list", 200)

    def test_get_trending_products(self):
        """Test get trending products"""
        return self.run_test("Get Trending Products", "GET", "products/trending/list", 200)

    def test_get_single_product(self):
        """Test get single product"""
        return self.run_test("Get Single Product", "GET", "products/p1", 200)

    def test_get_nonexistent_product(self):
        """Test get non-existent product"""
        return self.run_test("Get Non-existent Product", "GET", "products/nonexistent", 404)

    def test_create_cart(self):
        """Test create cart"""
        success, response = self.run_test("Create Cart", "POST", "cart", 200)
        if success and 'cart_id' in response:
            self.cart_id = response['cart_id']
            print(f"   Cart ID: {self.cart_id}")
        return success

    def test_add_to_cart(self):
        """Test add item to cart"""
        if not self.cart_id:
            print("❌ No cart ID available")
            return False
        
        data = {"product_id": "p1", "quantity": 2}
        return self.run_test("Add to Cart", "POST", f"cart/{self.cart_id}/items", 200, data)

    def test_get_cart(self):
        """Test get cart contents"""
        if not self.cart_id:
            print("❌ No cart ID available")
            return False
        
        return self.run_test("Get Cart", "GET", f"cart/{self.cart_id}", 200)

    def test_update_cart_item(self):
        """Test update cart item quantity"""
        if not self.cart_id:
            print("❌ No cart ID available")
            return False
        
        return self.run_test("Update Cart Item", "PUT", f"cart/{self.cart_id}/items/p1", 200, params={"quantity": 3})

    def test_remove_from_cart(self):
        """Test remove item from cart"""
        if not self.cart_id:
            print("❌ No cart ID available")
            return False
        
        return self.run_test("Remove from Cart", "DELETE", f"cart/{self.cart_id}/items/p1", 200)

    def test_email_subscription(self):
        """Test email subscription"""
        test_email = f"test_{datetime.now().strftime('%H%M%S')}@example.com"
        data = {"email": test_email}
        return self.run_test("Email Subscription", "POST", "subscribe", 200, data)

    def test_get_testimonials(self):
        """Test get testimonials"""
        return self.run_test("Get Testimonials", "GET", "testimonials", 200)

    def test_status_check(self):
        """Test status check endpoints"""
        # Create status check
        data = {"client_name": "test_client"}
        success1, _ = self.run_test("Create Status Check", "POST", "status", 200, data)
        
        # Get status checks
        success2, _ = self.run_test("Get Status Checks", "GET", "status", 200)
        
        return success1 and success2

def main():
    print("🚀 Starting LuxeAura API Tests...")
    print("=" * 50)
    
    tester = LuxeAuraAPITester()
    
    # Test sequence
    tests = [
        tester.test_api_root,
        tester.test_get_products,
        tester.test_get_new_arrivals,
        tester.test_get_trending_products,
        tester.test_get_single_product,
        tester.test_get_nonexistent_product,
        tester.test_get_testimonials,
        tester.test_create_cart,
        tester.test_add_to_cart,
        tester.test_get_cart,
        tester.test_update_cart_item,
        tester.test_remove_from_cart,
        tester.test_email_subscription,
        tester.test_status_check
    ]
    
    # Run all tests
    for test in tests:
        try:
            test()
        except Exception as e:
            print(f"❌ Test failed with exception: {str(e)}")
    
    # Print final results
    print("\n" + "=" * 50)
    print(f"📊 Final Results: {tester.tests_passed}/{tester.tests_run} tests passed")
    print(f"Success Rate: {(tester.tests_passed/tester.tests_run)*100:.1f}%")
    
    if tester.tests_passed == tester.tests_run:
        print("🎉 All tests passed!")
        return 0
    else:
        print("⚠️  Some tests failed")
        return 1

if __name__ == "__main__":
    sys.exit(main())