#!/usr/bin/env python3

import requests
import json
import sys
from datetime import datetime

class QueenCityAutoAPITester:
    def __init__(self, base_url="https://wholesale-auto-parts.preview.emergentagent.com/api"):
        self.base_url = base_url
        self.token = None
        self.tests_run = 0
        self.tests_passed = 0
        self.failed_tests = []
        
    def log(self, message, is_error=False):
        timestamp = datetime.now().strftime("%H:%M:%S")
        if is_error:
            print(f"[{timestamp}] ❌ {message}")
        else:
            print(f"[{timestamp}] {message}")
    
    def run_test(self, name, method, endpoint, expected_status, data=None, headers=None):
        """Run a single API test"""
        url = f"{self.base_url}/{endpoint}"
        
        # Default headers
        default_headers = {'Content-Type': 'application/json'}
        if self.token:
            default_headers['Authorization'] = f'Bearer {self.token}'
        
        # Merge with provided headers
        if headers:
            default_headers.update(headers)

        self.tests_run += 1
        self.log(f"🔍 Testing {name}...")
        
        try:
            if method == 'GET':
                response = requests.get(url, headers=default_headers, timeout=15)
            elif method == 'POST':
                response = requests.post(url, json=data, headers=default_headers, timeout=15)
            elif method == 'PATCH':
                response = requests.patch(url, json=data, headers=default_headers, timeout=15)
            elif method == 'DELETE':
                response = requests.delete(url, headers=default_headers, timeout=15)

            success = response.status_code == expected_status
            if success:
                self.tests_passed += 1
                self.log(f"  ✅ Passed - Status: {response.status_code}")
                try:
                    return True, response.json() if response.content else {}
                except:
                    return True, {}
            else:
                self.log(f"  ❌ Failed - Expected {expected_status}, got {response.status_code}", True)
                try:
                    error_detail = response.json()
                    self.log(f"  Error: {error_detail}", True)
                except:
                    self.log(f"  Response: {response.text}", True)
                    
                self.failed_tests.append(f"{name}: Expected {expected_status}, got {response.status_code}")
                return False, {}

        except Exception as e:
            self.log(f"  ❌ Failed - Error: {str(e)}", True)
            self.failed_tests.append(f"{name}: Exception - {str(e)}")
            return False, {}

    def test_admin_authentication(self):
        """Test admin login functionality"""
        self.log("\n🔐 TESTING ADMIN AUTHENTICATION")
        
        # Test invalid credentials
        success, _ = self.run_test(
            "Invalid Login",
            "POST", 
            "auth/login",
            401,
            data={"username": "wrong", "password": "wrong"}
        )
        
        # Test valid admin credentials
        success, response = self.run_test(
            "Valid Admin Login",
            "POST",
            "auth/login", 
            200,
            data={"username": "admin", "password": "queencity2024"}
        )
        
        if success and 'token' in response:
            self.token = response['token']
            self.log(f"  🎯 Token obtained successfully")
            
            # Test token validation
            success, _ = self.run_test(
                "Token Validation",
                "GET",
                "auth/me",
                200
            )
            return True
        return False

    def test_inventory_endpoints(self):
        """Test inventory management"""
        self.log("\n📦 TESTING INVENTORY ENDPOINTS")
        
        # Get inventory (public endpoint)
        success, inventory = self.run_test(
            "Get Inventory",
            "GET",
            "inventory",
            200
        )
        
        if success:
            self.log(f"  📊 Found {len(inventory)} inventory items")
            if len(inventory) >= 6:
                self.log(f"  ✅ Expected 6+ seeded items found")
            else:
                self.log(f"  ⚠️ Expected 6+ items, found {len(inventory)}", True)
                
        return success

    def test_testimonials_endpoint(self):
        """Test testimonials endpoint"""
        self.log("\n⭐ TESTING TESTIMONIALS ENDPOINT")
        
        success, testimonials = self.run_test(
            "Get Testimonials",
            "GET", 
            "testimonials",
            200
        )
        
        if success:
            self.log(f"  📊 Found {len(testimonials)} testimonials")
            if len(testimonials) >= 4:
                self.log(f"  ✅ Expected 4+ seeded testimonials found")
            else:
                self.log(f"  ⚠️ Expected 4+ testimonials, found {len(testimonials)}", True)
                
        return success

    def test_part_requests(self):
        """Test part request functionality"""  
        self.log("\n🔧 TESTING PART REQUESTS")
        
        # Create part request (public endpoint)
        test_request = {
            "vehicle_year": "2020",
            "make": "Toyota", 
            "model": "Camry",
            "engine": "2.5L 4cyl",
            "part_needed": "Driver side headlight assembly",
            "vin": "1HGBH41JXMN109186",
            "budget": "$200-300",
            "name": "Test Customer",
            "email": "test@example.com", 
            "phone": "(704) 555-9999",
            "notes": "Test part request from API testing"
        }
        
        success, created_request = self.run_test(
            "Create Part Request",
            "POST",
            "part-requests",
            200,
            data=test_request
        )
        
        if not success:
            return False
            
        request_id = created_request.get('id')
        self.log(f"  🆔 Created request with ID: {request_id}")
        
        # Get part requests (admin only)
        success, requests = self.run_test(
            "Get Part Requests (Admin)",
            "GET",
            "part-requests", 
            200
        )
        
        if success:
            self.log(f"  📊 Found {len(requests)} part requests")
            
        # Update part request status (admin only) 
        if request_id:
            success, updated = self.run_test(
                "Update Part Request Status",
                "PATCH",
                f"part-requests/{request_id}",
                200,
                data={"status": "in_progress", "quoted_price": 250.00, "cost_price": 150.00}
            )
            
            if success:
                profit = updated.get('profit', 0)
                self.log(f"  💰 Updated with profit calculation: ${profit}")
        
        return success

    def test_contact_endpoints(self):
        """Test contact functionality"""
        self.log("\n📞 TESTING CONTACT ENDPOINTS") 
        
        # Create contact submission (public)
        contact_data = {
            "name": "Test Contact",
            "email": "contact@example.com",
            "phone": "(704) 555-8888", 
            "message": "This is a test contact message from API testing."
        }
        
        success, _ = self.run_test(
            "Create Contact Submission",
            "POST",
            "contact",
            200,
            data=contact_data
        )
        
        # Get contacts (admin only)
        success, contacts = self.run_test(
            "Get Contacts (Admin)",
            "GET", 
            "contacts",
            200
        )
        
        if success:
            self.log(f"  📊 Found {len(contacts)} contact submissions")
            
        return success

    def test_dashboard_stats(self):
        """Test dashboard statistics"""
        self.log("\n📈 TESTING DASHBOARD STATS")
        
        success, stats = self.run_test(
            "Get Dashboard Stats (Admin)",
            "GET",
            "dashboard/stats", 
            200
        )
        
        if success:
            self.log(f"  📊 Stats: {json.dumps(stats, indent=2)}")
            required_fields = ['total_requests', 'new_requests', 'completed', 'total_revenue', 'total_profit', 'total_contacts']
            for field in required_fields:
                if field in stats:
                    self.log(f"  ✅ {field}: {stats[field]}")
                else:
                    self.log(f"  ❌ Missing field: {field}", True)
                    
        return success

    def test_vin_decoder(self):
        """Test VIN decoder functionality"""
        self.log("\n🔍 TESTING VIN DECODER")
        
        # Test with provided test VIN
        test_vin = "1HGBH41JXMN109186"
        
        success, vin_data = self.run_test(
            f"Decode VIN {test_vin}",
            "GET",
            f"vin-decode/{test_vin}",
            200
        )
        
        if success:
            self.log(f"  🚗 Decoded VIN data: {json.dumps(vin_data, indent=2)}")
            expected_fields = ['year', 'make', 'model', 'engine']
            for field in expected_fields:
                if field in vin_data and vin_data[field]:
                    self.log(f"  ✅ {field}: {vin_data[field]}")
                else:
                    self.log(f"  ⚠️ Empty or missing field: {field}")
        
        # Test invalid VIN
        success, _ = self.run_test(
            "Invalid VIN (too short)",
            "GET", 
            "vin-decode/123",
            400
        )
                    
        return success

    def test_file_upload(self):
        """Test file upload functionality"""
        self.log("\n📁 TESTING FILE UPLOAD")
        
        # Create a small test file in memory
        files = {'file': ('test.txt', b'test file content', 'text/plain')}
        
        try:
            response = requests.post(
                f"{self.base_url}/upload",
                files=files,
                headers={'Authorization': f'Bearer {self.token}'},
                timeout=10
            )
            
            if response.status_code == 200:
                upload_data = response.json()
                self.log(f"  ✅ File upload successful: {upload_data.get('url', 'No URL')}")
                self.tests_passed += 1
            else:
                self.log(f"  ❌ Upload failed with status {response.status_code}", True)
                self.failed_tests.append(f"File Upload: Expected 200, got {response.status_code}")
                
            self.tests_run += 1
            return response.status_code == 200
            
        except Exception as e:
            self.log(f"  ❌ Upload error: {str(e)}", True)
            self.failed_tests.append(f"File Upload: Exception - {str(e)}")
            self.tests_run += 1
            return False

def main():
    """Main test execution"""
    print("🚀 Starting Queen City Auto Sourcing API Tests")
    print("=" * 60)
    
    tester = QueenCityAutoAPITester()
    
    # Run all tests
    tests = [
        tester.test_admin_authentication,
        tester.test_inventory_endpoints,
        tester.test_testimonials_endpoint, 
        tester.test_part_requests,
        tester.test_contact_endpoints,
        tester.test_dashboard_stats,
        tester.test_vin_decoder,
        tester.test_file_upload
    ]
    
    for test in tests:
        try:
            test()
        except Exception as e:
            tester.log(f"Test suite error: {str(e)}", True)
    
    # Print final results
    print("\n" + "=" * 60)
    print("🏁 TEST SUMMARY")
    print("=" * 60)
    print(f"Total Tests: {tester.tests_run}")
    print(f"Passed: {tester.tests_passed}")
    print(f"Failed: {len(tester.failed_tests)}")
    print(f"Success Rate: {(tester.tests_passed/tester.tests_run*100):.1f}%" if tester.tests_run > 0 else "0%")
    
    if tester.failed_tests:
        print(f"\n❌ Failed Tests:")
        for failure in tester.failed_tests:
            print(f"  - {failure}")
    else:
        print(f"\n✅ All tests passed!")
        
    return 0 if len(tester.failed_tests) == 0 else 1

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