# python manage.py shell < test_onesignal_auth.py
import os
import requests
import json

api_key = os.environ.get('ONESIGNAL_REST_API_KEY', '').strip()
app_id = "e93f40d7-08e7-4345-aaa0-c0bff6397a16"

print("\n" + "="*60)
print(f"🚀 VIDESH CHALO: Final Push Verification v4.0")
print("="*60)

headers = {"Authorization": f"Basic {api_key}", "Content-Type": "application/json"}

try:
    # 📡 1. Fetching Detailed Player Data
    url_players = f"https://onesignal.com/api/v1/players?app_id={app_id}"
    res_players = requests.get(url_players, headers=headers, timeout=15)
    
    if res_players.status_code == 200:
        players_data = res_players.json()
        all_players = players_data.get('players', [])
        
        print(f"📊 SYSTEM STATUS:")
        print(f"   - Total Registered Devices: {len(all_players)}")
        
        active_ids = []
        for p in all_players:
            device_type = "📱 Mobile/PWA" if p.get('device_type') in [0, 1] else "💻 Desktop"
            status = "✅ Active" if not p.get('invalid_identifier') else "❌ Inactive/Blocked"
            print(f"   - Device: {device_type} | Status: {status} | ID: {p['id'][:8]}...")
            
            if not p.get('invalid_identifier'):
                active_ids.append(p['id'])

        # 🔔 2. TRIGGERING NOTIFICATION
        if active_ids:
            print(f"\n📡 Sending Notification to {len(active_ids)} active devices...")
            payload = {
                "app_id": app_id,
                "include_player_ids": active_ids,
                "headings": {"en": "Ram Ram Bhai! ✈️"},
                "contents": {"en": "Mobile par aa gaya? Ab Desktop check karein!"},
                "url": "https://www.videshchalo.com",
                "chrome_web_icon": "https://www.videshchalo.com/static/images/videsh_chalo_logo.png"
            }
            
            res_push = requests.post("https://onesignal.com/api/v1/notifications", headers=headers, json=payload)
            push_res = res_push.json()

            if res_push.status_code == 200:
                # 💡 Note: OneSignal sometimes returns 0 recipients in immediate response 
                # while processing. If mobile got it, the system is working!
                print(f"🚀 SUCCESS: API Accepted the request (ID: {push_res.get('id')})")
                print(f"✨ BHAI, AGAR MOBILE PE AA GAYA HAI TOH SYSTEM OK HAI!")
            else:
                print(f"❌ PUSH ERROR: {res_push.text}")
        else:
            print("\n❌ NO ACTIVE USERS: Please allow notifications in your browser first.")

    else:
        print(f"❌ AUTH ERROR: Status {res_players.status_code}")

except Exception as e:
    print(f"🔥 CRITICAL ERROR: {e}")

print("\n" + "="*60 + "\n")