#!/usr/bin/env python3
"""
ParentZone API Test Script

This script tests the ParentZone API integration specifically.
"""

import asyncio
import aiohttp
import json
from urllib.parse import urljoin


async def test_parentzone_api():
    """Test the ParentZone API with the provided API key."""
    api_url = "https://api.parentzone.me"
    list_endpoint = "/v1/gallery"
    download_endpoint = "/v1/media"
    api_key = "b23326a9-bcbf-4bad-b026-9c79dad6a654"
    
    headers = {
        'x-api-key': api_key
    }
    
    print("=" * 60)
    print("ParentZone API Test")
    print("=" * 60)
    
    timeout = aiohttp.ClientTimeout(total=30)
    async with aiohttp.ClientSession(timeout=timeout) as session:
        # Test list endpoint
        list_url = urljoin(api_url, list_endpoint)
        print(f"Testing list endpoint: {list_url}")
        
        try:
            async with session.get(list_url, headers=headers) as response:
                print(f"Status Code: {response.status}")
                print(f"Content-Type: {response.headers.get('content-type', 'Not specified')}")
                
                if response.status == 200:
                    data = await response.json()
                    print(f"Response type: {type(data)}")
                    
                    if isinstance(data, list):
                        print(f"✓ Found {len(data)} assets in array")
                        if data:
                            print(f"First asset keys: {list(data[0].keys())}")
                            print(f"Sample asset: {json.dumps(data[0], indent=2)}")
                            
                            # Test download endpoint with first asset
                            asset_id = data[0].get('id')
                            updated = data[0].get('updated', '')
                            if asset_id:
                                print(f"\nTesting download endpoint with asset ID: {asset_id}")
                                from urllib.parse import urlencode
                                params = {
                                    'key': api_key,
                                    'u': updated
                                }
                                download_url = urljoin(api_url, f"/v1/media/{asset_id}/full?{urlencode(params)}")
                                print(f"Download URL: {download_url}")
                                
                                async with session.get(download_url) as download_response:
                                    print(f"Download Status Code: {download_response.status}")
                                    print(f"Download Content-Type: {download_response.headers.get('content-type', 'Not specified')}")
                                    print(f"Download Content-Length: {download_response.headers.get('content-length', 'Not specified')}")
                                    
                                    if download_response.status == 200:
                                        content_type = download_response.headers.get('content-type', '')
                                        if content_type.startswith('image/'):
                                            print("✓ Download endpoint returns image content")
                                        else:
                                            print(f"⚠ Warning: Content type is not an image: {content_type}")
                                    else:
                                        print(f"✗ Download endpoint failed: HTTP {download_response.status}")
                            else:
                                print("⚠ No asset ID found in first asset")
                    else:
                        print(f"✗ Unexpected response format: {type(data)}")
                else:
                    print(f"✗ List endpoint failed: HTTP {response.status}")
                    
        except Exception as e:
            print(f"✗ Error testing API: {e}")
    
    print("\n" + "=" * 60)
    print("TEST COMPLETE")
    print("=" * 60)


if __name__ == "__main__":
    asyncio.run(test_parentzone_api())
