"""
Test Microsoft Planetary Computer connectivity và token
"""
import planetary_computer
from pystac_client import Client
from datetime import datetime, timedelta

print("=" * 70)
print("🧪 TESTING MICROSOFT PLANETARY COMPUTER CONNECTION")
print("=" * 70)

# Test 1: Basic connection
print("\n1️⃣ Testing basic connection...")
try:
    catalog = Client.open(
        "https://planetarycomputer.microsoft.com/api/stac/v1",
        modifier=planetary_computer.sign_inplace,
    )
    print("✅ Successfully connected to Planetary Computer")
    print(f"   Catalog ID: {catalog.id}")
    print(f"   Title: {catalog.title}")
except Exception as e:
    print(f"❌ Connection failed: {e}")
    exit(1)

# Test 2: List collections
print("\n2️⃣ Testing collections access...")
try:
    collections = list(catalog.get_collections())
    print(f"✅ Found {len(collections)} collections")
    sentinel_2 = [c for c in collections if 'sentinel-2' in c.id.lower()]
    print(f"   Sentinel-2 collections: {[c.id for c in sentinel_2]}")
except Exception as e:
    print(f"❌ Collections access failed: {e}")

# Test 3: Small search query (very conservative)
print("\n3️⃣ Testing small search query...")
try:
    # Tiny bbox in Vietnam
    bbox = [105.8, 10.0, 105.9, 10.1]  # ~10km x 10km area
    end_date = datetime.now()
    start_date = end_date - timedelta(days=7)  # Last 7 days only
    
    time_range = f"{start_date.strftime('%Y-%m-%d')}/{end_date.strftime('%Y-%m-%d')}"
    
    print(f"   Bbox: {bbox}")
    print(f"   Time: {time_range}")
    print(f"   Searching...")
    
    search = catalog.search(
        collections=["sentinel-2-l2a"],
        bbox=bbox,
        datetime=time_range,
        limit=5  # Only 5 items
    )
    
    items = []
    for i, item in enumerate(search.items()):
        items.append(item)
        if i >= 4:  # Stop at 5
            break
    
    print(f"✅ Search successful! Found {len(items)} items")
    if items:
        first_item = items[0]
        print(f"   First item: {first_item.id}")
        print(f"   Date: {first_item.datetime}")
        
        # Test token signing
        signed_item = planetary_computer.sign(first_item)
        print(f"✅ SAS token signing works")
        print(f"   Asset keys: {list(signed_item.assets.keys())[:5]}")
        
except Exception as e:
    print(f"❌ Search failed: {e}")
    import traceback
    traceback.print_exc()

print("\n" + "=" * 70)
print("🏁 Test completed!")
print("=" * 70)
print("\n💡 Nếu test này PASS:")
print("   → Planetary Computer hoạt động bình thường")
print("   → Vấn đề là query quá lớn (bbox/time range/max_scenes)")
print("\n💡 Nếu test này FAIL:")
print("   → Kiểm tra internet connection")
print("   → Thử lại sau (server có thể bị quá tải)")
print("   → Xem xét dùng dữ liệu local")
