#!/usr/bin/env python3
"""Quick test for Maton API key"""
import urllib.request
import os
import json

def test_maton_key():
    try:
        # Check if MATON_API_KEY env var exists
        api_key = os.environ.get('MATON_API_KEY')
        if not api_key:
            print("❌ MATON_API_KEY environment variable not set")
            print("To set it, run: export MATON_API_KEY='your_key_here'")
            return False
        
        print(f"🔑 Testing API key: {api_key[:15]}...")
        
        # Test the API key by listing connections
        req = urllib.request.Request('https://ctrl.maton.ai/connections')
        req.add_header('Authorization', f'Bearer {api_key}')
        
        response = urllib.request.urlopen(req, timeout=10)
        data = json.load(response)
        
        print("✅ Maton API key is working!")
        connections = data.get('connections', [])
        print(f"Found {len(connections)} connections:")
        
        if connections:
            for conn in connections:
                status_emoji = "✅" if conn.get('status') == 'ACTIVE' else "⚠️" 
                app_name = conn.get('app', 'Unknown')
                status = conn.get('status', 'Unknown')
                created = conn.get('creation_time', '')[:10] if conn.get('creation_time') else 'Unknown'
                print(f"  {status_emoji} {app_name} ({status}) - created {created}")
        else:
            print("  (No connections yet - you can create some at maton.ai)")
            
        return True
        
    except urllib.error.HTTPError as e:
        print(f"❌ HTTP Error {e.code}: {e.reason}")
        if e.code == 401:
            print("   → Invalid API key or expired")
            print("   → Get a new one at: https://maton.ai/settings")
        elif e.code == 429:
            print("   → Rate limited (10 req/sec)")
        else:
            try:
                error_body = e.read().decode()
                print(f"   → {error_body}")
            except:
                print("   → Unknown error")
        return False
    except Exception as e:
        print(f"❌ Error: {e}")
        print("Possible causes:")
        print("  1. MATON_API_KEY not set in environment")
        print("  2. Invalid API key")
        print("  3. Network/connectivity issue")
        return False

if __name__ == "__main__":
    test_maton_key()