#!/usr/bin/env python3
"""
Comprehensive test for AgentBeats assets system including uploads and SDK functionality.
"""

import os
import tempfile
import requests
import sys
from pathlib import Path

# Add the assets module to the path
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'src', 'agentbeats', 'utils', 'assets'))

from assets import static_expose

def test_uploads_system():
    """Test the uploads system via direct API calls."""
    
    print("Testing AgentBeats Uploads System...")
    
    # Test server URL
    base_url = "http://localhost:9000"
    
    try:
        # Test 1: Upload user avatar
        print("\n1. Testing user avatar upload...")
        
        # Create a test image
        with tempfile.NamedTemporaryFile(mode='w', suffix='.svg', delete=False) as f:
            f.write('''<?xml version="1.0" encoding="UTF-8"?>
<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">
  <circle cx="50" cy="50" r="40" fill="#4CAF50"/>
  <text x="50" y="55" text-anchor="middle" fill="white" font-family="Arial" font-size="12">User</text>
</svg>''')
            test_image = f.name
        
        try:
            with open(test_image, 'rb') as f:
                files = {'file': ('test_avatar.svg', f, 'image/svg+xml')}
                data = {'user_id': 'test_user_123'}
                
                response = requests.post(f"{base_url}/assets/uploads/avatar/user", files=files, data=data)
                
                if response.status_code == 200:
                    result = response.json()
                    print(f"✓ User avatar uploaded: {result['url']}")
                    
                    # Test retrieving the avatar
                    avatar_response = requests.get(f"{base_url}{result['url']}")
                    if avatar_response.status_code == 200:
                        print("✓ User avatar retrieved successfully")
                    else:
                        print(f"✗ Failed to retrieve avatar: {avatar_response.status_code}")
                else:
                    print(f"✗ User avatar upload failed: {response.status_code} - {response.text}")
        finally:
            if os.path.exists(test_image):
                os.unlink(test_image)
        
        # Test 2: Upload agent avatar
        print("\n2. Testing agent avatar upload...")
        
        with tempfile.NamedTemporaryFile(mode='w', suffix='.svg', delete=False) as f:
            f.write('''<?xml version="1.0" encoding="UTF-8"?>
<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">
  <rect width="100" height="100" fill="#2196F3"/>
  <text x="50" y="55" text-anchor="middle" fill="white" font-family="Arial" font-size="12">Agent</text>
</svg>''')
            test_image = f.name
        
        try:
            with open(test_image, 'rb') as f:
                files = {'file': ('test_agent.svg', f, 'image/svg+xml')}
                data = {'agent_id': 'test_agent_456'}
                
                response = requests.post(f"{base_url}/assets/uploads/avatar/agent", files=files, data=data)
                
                if response.status_code == 200:
                    result = response.json()
                    print(f"✓ Agent avatar uploaded: {result['url']}")
                else:
                    print(f"✗ Agent avatar upload failed: {response.status_code} - {response.text}")
        finally:
            if os.path.exists(test_image):
                os.unlink(test_image)
        
        # Test 3: Upload battle asset
        print("\n3. Testing battle asset upload...")
        
        battle_id = "test_battle_789"
        
        with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as f:
            f.write("This is a test battle report.\nGenerated by test script.\n")
            test_file = f.name
        
        try:
            with open(test_file, 'rb') as f:
                files = {'file': ('test_report.txt', f, 'text/plain')}
                data = {
                    'asset_name': 'battle_report.txt',
                    'uploaded_by': 'test_agent'
                }
                
                response = requests.post(f"{base_url}/assets/uploads/battle/{battle_id}", files=files, data=data)
                
                if response.status_code == 200:
                    result = response.json()
                    print(f"✓ Battle asset uploaded: {result['url']}")
                    
                    # Test retrieving the battle asset
                    asset_response = requests.get(f"{base_url}{result['url']}")
                    if asset_response.status_code == 200:
                        print("✓ Battle asset retrieved successfully")
                        print(f"  Content: {asset_response.text[:50]}...")
                    else:
                        print(f"✗ Failed to retrieve battle asset: {asset_response.status_code}")
                else:
                    print(f"✗ Battle asset upload failed: {response.status_code} - {response.text}")
        finally:
            if os.path.exists(test_file):
                os.unlink(test_file)
        
        # Test 4: List assets
        print("\n4. Testing asset listing...")
        
        response = requests.get(f"{base_url}/assets/uploads/assets")
        if response.status_code == 200:
            result = response.json()
            print(f"✓ Found {result['count']} assets")
            for asset in result['assets'][:3]:  # Show first 3
                print(f"  - {asset['asset_name']} ({asset['category']})")
        else:
            print(f"✗ Failed to list assets: {response.status_code}")
        
        print("\n🎉 Uploads system test completed!")
        return True
        
    except requests.exceptions.ConnectionError:
        print("✗ Could not connect to server. Make sure the backend is running on localhost:9000")
        return False
    except Exception as e:
        print(f"✗ Test failed: {str(e)}")
        return False

def test_sdk_functionality():
    """Test the SDK assets functionality."""
    
    print("\n" + "="*60)
    print("Testing AgentBeats Assets SDK...")
    print("="*60)
    
    # Test server URL
    ASSET_SERVER_URL = "http://localhost:9000"
    
    try:
        # Test 1: Create a test file
        print("\n1. Creating test file...")
        
        with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as f:
            f.write("This is a test battle report.\nGenerated by SDK test.\n")
            test_file = f.name
        
        try:
            print(f"✓ Test file created: {test_file}")
            
            # Test 2: Upload battle asset using SDK
            print("\n2. Testing SDK battle asset upload...")
            
            battle_id = "sdk_test_battle_001"
            uploaded_by = "test_agent"
            
            url = static_expose(
                file_path=test_file,
                asset_name="sdk_test_report.txt",
                battle_id=battle_id,
                uploaded_by=uploaded_by,
                backend_url=ASSET_SERVER_URL
            )
            
            if url:
                print(f"✓ Battle asset uploaded: {url}")
                
                # Test 3: Retrieve the uploaded asset
                print("\n3. Testing asset retrieval...")
                
                response = requests.get(url)
                if response.status_code == 200:
                    print("✓ Asset retrieved successfully")
                    print(f"  Content: {response.text[:50]}...")
                else:
                    print(f"✗ Failed to retrieve asset: {response.status_code}")
            else:
                print("✗ Asset upload failed")
                
        finally:
            if os.path.exists(test_file):
                os.unlink(test_file)
        
        # Test 4: List assets and find SDK test assets
        print("\n4. Testing asset listing...")
        
        response = requests.get(f"{ASSET_SERVER_URL}/assets/uploads/assets")
        if response.status_code == 200:
            result = response.json()
            print(f"✓ Found {result['count']} assets")
            
            # Find our SDK test asset
            sdk_assets = [a for a in result['assets'] if 'sdk_test' in a.get('asset_name', '')]
            if sdk_assets:
                print(f"✓ Found {len(sdk_assets)} SDK test assets")
                for asset in sdk_assets:
                    print(f"  - {asset['asset_name']} ({asset['category']})")
            else:
                print("  No SDK test assets found")
        else:
            print(f"✗ Failed to list assets: {response.status_code}")
        
        # Test 5: Test asset categories endpoint
        print("\n5. Testing asset categories...")
        
        response = requests.get(f"{ASSET_SERVER_URL}/assets/list")
        if response.status_code == 200:
            result = response.json()
            print("✓ Asset categories retrieved:")
            for category, info in result['categories'].items():
                print(f"  - {category}: {info['description']}")
        else:
            print(f"✗ Failed to get asset categories: {response.status_code}")
        
        print("\n🎉 Assets SDK test completed!")
        return True
        
    except requests.exceptions.ConnectionError:
        print("✗ Could not connect to server. Make sure the backend is running on localhost:9000")
        return False
    except Exception as e:
        print(f"✗ Test failed: {str(e)}")
        return False

def test_static_assets():
    """Test static assets functionality."""
    
    print("\n" + "="*60)
    print("Testing Static Assets...")
    print("="*60)
    
    base_url = "http://localhost:9000"
    
    try:
        # Test 1: Create a test static file
        print("\n1. Creating test static file...")
        
        static_dir = "../../src/backend/assets/static/images"
        os.makedirs(static_dir, exist_ok=True)
        
        test_static_file = os.path.join(static_dir, "test_logo.svg")
        with open(test_static_file, 'w') as f:
            f.write('''<?xml version="1.0" encoding="UTF-8"?>
<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">
  <rect width="100" height="100" fill="#FF5722"/>
  <text x="50" y="55" text-anchor="middle" fill="white" font-family="Arial" font-size="12">Logo</text>
</svg>''')
        
        print(f"✓ Test static file created: {test_static_file}")
        
        # Test 2: Access static file via API
        print("\n2. Testing static file access...")
        
        response = requests.get(f"{base_url}/assets/static/images/test_logo.svg")
        if response.status_code == 200:
            print("✓ Static file accessed successfully")
            print(f"  Content length: {len(response.content)} bytes")
        else:
            print(f"✗ Failed to access static file: {response.status_code}")
        
        # Test 3: Test non-existent static file
        print("\n3. Testing non-existent static file...")
        
        response = requests.get(f"{base_url}/assets/static/images/nonexistent.png")
        if response.status_code == 404:
            print("✓ Correctly returned 404 for non-existent file")
        else:
            print(f"✗ Unexpected response for non-existent file: {response.status_code}")
        
        print("\n🎉 Static assets test completed!")
        return True
        
    except Exception as e:
        print(f"✗ Test failed: {str(e)}")
        return False

def main():
    """Run all tests."""
    
    print("🚀 Starting AgentBeats Assets System Tests")
    print("="*60)
    
    # Run all tests
    tests = [
        ("Uploads System", test_uploads_system),
        ("SDK Functionality", test_sdk_functionality),
        ("Static Assets", test_static_assets)
    ]
    
    results = []
    for test_name, test_func in tests:
        try:
            result = test_func()
            results.append((test_name, result))
        except Exception as e:
            print(f"✗ {test_name} test crashed: {str(e)}")
            results.append((test_name, False))
    
    # Summary
    print("\n" + "="*60)
    print("📊 TEST SUMMARY")
    print("="*60)
    
    passed = 0
    total = len(results)
    
    for test_name, result in results:
        status = "✅ PASSED" if result else "❌ FAILED"
        print(f"{test_name}: {status}")
        if result:
            passed += 1
    
    print(f"\nOverall: {passed}/{total} tests passed")
    
    if passed == total:
        print("🎉 All tests passed! Assets system is working correctly.")
        return True
    else:
        print("⚠️  Some tests failed. Please check the output above.")
        return False

if __name__ == "__main__":
    success = main()
    exit(0 if success else 1) 