import urllib.request
import json
import ssl
import sys

def run_diagnostic():
    key_id = "AKCNONH5XLDSBV47BVVDLISPNN"
    secret_key = "8SzLBuBHeDXGRKzkrvgv2cgAVnACxp6cVD3CME5299we"

    # Direct authentic path to live account services
    url = 'https://api.alpaca.markets/v2/account'
    req = urllib.request.Request(url)
    
    # 🛡️ THE COMPLETE FIXED PRODUCTION HEADER MATRIX
    req.add_header('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)')
    req.add_header('Accept', 'application/json')
    req.add_header('APCA-API-KEY-ID', key_id)
    req.add_header('APCA-API-SECRET-KEY', secret_key)
    
    ctx = ssl.create_default_context()
    ctx.check_hostname = False
    ctx.verify_mode = ssl.CERT_NONE
    
    print('Connecting directly to live funded Alpaca brokerage systems...')
    try:
        with urllib.request.urlopen(req, timeout=5, context=ctx) as response:
            res_body = response.read().decode()
            
            # Check if empty string returned
            if not res_body.strip():
                print("❌ Received an empty response from the live server exchange.")
                return
                
            data = json.loads(res_body)
            print('\n🏆 === ALPACA LIVE CONNECTION SUCCESS ===')
            print(f'Account Status   : {data.get("status")}')
            print(f'Trading Class    : {data.get("trading_type")}')
            print(f'Live Buying Power: ${data.get("buying_power")}')
            print(f'Cash Balance     : ${data.get("cash")}')
            print('=======================================')
            print('Your live trading keys are 100% authenticated and online!')
    except Exception as e:
        print('\n=== ❌ ALPACA LIVE CONNECTION DENIED ===')
        if hasattr(e, 'read'):
            err_data = e.read().decode()
            print(f'Exchange Error Payload: {err_data}')
        else:
            print(f'Connection Error Details: {e}')

if __name__ == '__main__':
    run_diagnostic()
