"""
Test script for project thumbnail functionality.
"""
import requests
import os
from pathlib import Path

# Configuration
BASE_URL = "http://localhost:8000/api"
TEST_IMAGE_PATH = Path(__file__).parent / "test_thumbnail.jpg"

def create_test_image():
    """Create a simple test image using PIL."""
    from PIL import Image
    
    # Create a simple 400x300 test image
    img = Image.new('RGB', (400, 300), color=(73, 109, 137))
    img.save(TEST_IMAGE_PATH, 'JPEG')
    print(f"✓ Created test image: {TEST_IMAGE_PATH}")

def login():
    """Login and get access token."""
    response = requests.post(
        f"{BASE_URL}/auth/login",
        data={
            "username": "admin@example.com",
            "password": "admin123"
        }
    )
    
    if response.status_code == 200:
        token = response.json()["access_token"]
        print("✓ Logged in successfully")
        return token
    else:
        print(f"✗ Login failed: {response.status_code}")
        print(response.text)
        return None

def get_projects(token):
    """Get list of projects."""
    headers = {"Authorization": f"Bearer {token}"}
    response = requests.get(f"{BASE_URL}/projects/", headers=headers)
    
    if response.status_code == 200:
        projects = response.json()
        print(f"✓ Retrieved {len(projects)} projects")
        return projects
    else:
        print(f"✗ Failed to get projects: {response.status_code}")
        return []

def upload_thumbnail(token, project_id):
    """Upload a thumbnail for a project."""
    headers = {"Authorization": f"Bearer {token}"}
    
    with open(TEST_IMAGE_PATH, 'rb') as f:
        files = {'file': ('test_thumbnail.jpg', f, 'image/jpeg')}
        response = requests.post(
            f"{BASE_URL}/projects/{project_id}/thumbnail",
            headers=headers,
            files=files
        )
    
    if response.status_code == 201:
        result = response.json()
        print(f"✓ Uploaded thumbnail successfully")
        print(f"  Thumbnail URL: {result.get('thumbnail_url')}")
        return True
    else:
        print(f"✗ Failed to upload thumbnail: {response.status_code}")
        print(response.text)
        return False

def get_project_with_thumbnail(token, project_id):
    """Get project details to verify thumbnail URL."""
    headers = {"Authorization": f"Bearer {token}"}
    response = requests.get(f"{BASE_URL}/projects/{project_id}", headers=headers)
    
    if response.status_code == 200:
        project = response.json()
        thumbnail_url = project.get('thumbnail_url')
        if thumbnail_url:
            print(f"✓ Project has thumbnail URL: {thumbnail_url}")
            return thumbnail_url
        else:
            print("✗ Project has no thumbnail URL")
            return None
    else:
        print(f"✗ Failed to get project: {response.status_code}")
        return None

def download_thumbnail(token, project_id):
    """Download and verify thumbnail."""
    headers = {"Authorization": f"Bearer {token}"}
    response = requests.get(
        f"{BASE_URL}/files/projects/{project_id}/thumbnail",
        headers=headers
    )
    
    if response.status_code == 200:
        print(f"✓ Downloaded thumbnail successfully")
        print(f"  Content-Type: {response.headers.get('content-type')}")
        print(f"  Size: {len(response.content)} bytes")
        return True
    else:
        print(f"✗ Failed to download thumbnail: {response.status_code}")
        print(response.text)
        return False

def delete_thumbnail(token, project_id):
    """Delete project thumbnail."""
    headers = {"Authorization": f"Bearer {token}"}
    response = requests.delete(
        f"{BASE_URL}/projects/{project_id}/thumbnail",
        headers=headers
    )
    
    if response.status_code == 204:
        print(f"✓ Deleted thumbnail successfully")
        return True
    else:
        print(f"✗ Failed to delete thumbnail: {response.status_code}")
        print(response.text)
        return False

def cleanup():
    """Clean up test files."""
    if TEST_IMAGE_PATH.exists():
        TEST_IMAGE_PATH.unlink()
        print("✓ Cleaned up test image")

def main():
    """Run all tests."""
    print("=" * 60)
    print("Testing Project Thumbnail Functionality")
    print("=" * 60)
    
    try:
        # Create test image
        create_test_image()
        
        # Login
        token = login()
        if not token:
            return
        
        # Get projects
        projects = get_projects(token)
        if not projects:
            print("✗ No projects found. Please create a project first.")
            return
        
        project_id = projects[0]['id']
        project_name = projects[0]['name']
        print(f"\nTesting with project: {project_name} (ID: {project_id})")
        print("-" * 60)
        
        # Test 1: Upload thumbnail
        print("\n1. Testing thumbnail upload...")
        if not upload_thumbnail(token, project_id):
            return
        
        # Test 2: Verify thumbnail URL in project response
        print("\n2. Verifying thumbnail URL in project response...")
        thumbnail_url = get_project_with_thumbnail(token, project_id)
        if not thumbnail_url:
            return
        
        # Test 3: Download thumbnail
        print("\n3. Testing thumbnail download...")
        if not download_thumbnail(token, project_id):
            return
        
        # Test 4: Delete thumbnail
        print("\n4. Testing thumbnail deletion...")
        if not delete_thumbnail(token, project_id):
            return
        
        # Test 5: Verify thumbnail is removed
        print("\n5. Verifying thumbnail is removed...")
        thumbnail_url = get_project_with_thumbnail(token, project_id)
        if thumbnail_url:
            print("✗ Thumbnail URL still exists after deletion")
        else:
            print("✓ Thumbnail URL correctly removed")
        
        print("\n" + "=" * 60)
        print("All tests completed successfully!")
        print("=" * 60)
        
    except Exception as e:
        print(f"\n✗ Error during testing: {e}")
        import traceback
        traceback.print_exc()
    
    finally:
        cleanup()

if __name__ == "__main__":
    main()
