import requests
import sys
from datetime import datetime

class ISPAPITester:
    def __init__(self, base_url="https://velocity-isp.preview.emergentagent.com"):
        self.base_url = base_url
        self.tests_run = 0
        self.tests_passed = 0

    def run_test(self, name, method, endpoint, expected_status, data=None, expected_fields=None):
        """Run a single API test"""
        url = f"{self.base_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, timeout=10)
            elif method == 'POST':
                response = requests.post(url, json=data, headers=headers, timeout=10)

            print(f"   Status Code: {response.status_code}")
            
            success = response.status_code == expected_status
            if success:
                self.tests_passed += 1
                print(f"✅ Passed - Status: {response.status_code}")
                
                # Check response content if expected_fields provided
                if expected_fields:
                    try:
                        response_data = response.json()
                        if isinstance(expected_fields, list):
                            # Check if response is a list and has expected structure
                            if isinstance(response_data, list) and len(response_data) > 0:
                                for field in expected_fields:
                                    if field not in response_data[0]:
                                        print(f"⚠️  Warning: Missing field '{field}' in response")
                                    else:
                                        print(f"   ✓ Field '{field}' present")
                            else:
                                print(f"⚠️  Warning: Expected list response, got {type(response_data)}")
                        elif isinstance(expected_fields, dict):
                            # Check if response has expected fields
                            for field in expected_fields:
                                if field not in response_data:
                                    print(f"⚠️  Warning: Missing field '{field}' in response")
                                else:
                                    print(f"   ✓ Field '{field}' present")
                    except Exception as e:
                        print(f"⚠️  Warning: Could not parse JSON response: {e}")
                
                return True, response.json() if response.content else {}
            else:
                print(f"❌ Failed - Expected {expected_status}, got {response.status_code}")
                if response.content:
                    print(f"   Response: {response.text[:200]}...")
                return False, {}

        except requests.exceptions.Timeout:
            print(f"❌ Failed - Request timeout")
            return False, {}
        except requests.exceptions.ConnectionError:
            print(f"❌ Failed - Connection error")
            return False, {}
        except Exception as e:
            print(f"❌ Failed - Error: {str(e)}")
            return False, {}

    def test_root_endpoint(self):
        """Test root API endpoint"""
        return self.run_test(
            "Root API Endpoint",
            "GET",
            "api/",
            200,
            expected_fields={"message"}
        )

    def test_packages_endpoint(self):
        """Test packages endpoint"""
        expected_fields = ["id", "name", "speed", "price", "features", "popular"]
        success, response = self.run_test(
            "Packages Endpoint",
            "GET",
            "api/packages",
            200,
            expected_fields=expected_fields
        )
        
        if success and response:
            print(f"   📦 Found {len(response)} packages")
            # Check for premium package with popular flag
            premium_found = any(pkg.get('popular', False) for pkg in response)
            if premium_found:
                print(f"   ✓ Premium package with 'popular' flag found")
            else:
                print(f"   ⚠️  No package marked as 'popular'")
        
        return success

    def test_testimonials_endpoint(self):
        """Test testimonials endpoint"""
        expected_fields = ["id", "name", "role", "content", "rating", "image"]
        success, response = self.run_test(
            "Testimonials Endpoint",
            "GET",
            "api/testimonials",
            200,
            expected_fields=expected_fields
        )
        
        if success and response:
            print(f"   💬 Found {len(response)} testimonials")
            # Check ratings
            ratings = [t.get('rating', 0) for t in response]
            avg_rating = sum(ratings) / len(ratings) if ratings else 0
            print(f"   ⭐ Average rating: {avg_rating:.1f}/5")
        
        return success

    def test_stats_endpoint(self):
        """Test stats endpoint"""
        expected_fields = {"active_users", "uptime", "avg_speed", "coverage_areas"}
        success, response = self.run_test(
            "Stats Endpoint",
            "GET",
            "api/stats",
            200,
            expected_fields=expected_fields
        )
        
        if success and response:
            print(f"   📊 Stats: Users={response.get('active_users')}, Uptime={response.get('uptime')}%, Speed={response.get('avg_speed')}Mbps, Areas={response.get('coverage_areas')}")
        
        return success

    def test_contact_endpoint(self):
        """Test contact form submission"""
        test_data = {
            "name": f"Test User {datetime.now().strftime('%H%M%S')}",
            "phone": "+8801234567890",
            "location": "Zindabazar, Sylhet",
            "message": "Test message for API testing"
        }
        
        success, response = self.run_test(
            "Contact Form Submission",
            "POST",
            "api/contact",
            200,
            data=test_data,
            expected_fields={"id", "name", "phone", "location", "message", "timestamp"}
        )
        
        if success and response:
            print(f"   📝 Contact submitted with ID: {response.get('id', 'N/A')}")
        
        return success

def main():
    print("🚀 Starting ISP Website API Testing...")
    print("=" * 50)
    
    # Setup
    tester = ISPAPITester()
    
    # Run all tests
    tests = [
        tester.test_root_endpoint,
        tester.test_packages_endpoint,
        tester.test_testimonials_endpoint,
        tester.test_stats_endpoint,
        tester.test_contact_endpoint
    ]
    
    for test in tests:
        test()
    
    # Print final results
    print("\n" + "=" * 50)
    print(f"📊 Final Results: {tester.tests_passed}/{tester.tests_run} tests passed")
    
    if tester.tests_passed == tester.tests_run:
        print("🎉 All tests passed! Backend APIs are working correctly.")
        return 0
    else:
        print(f"⚠️  {tester.tests_run - tester.tests_passed} test(s) failed.")
        return 1

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