#!/usr/bin/env python3
"""Test semplice connessione MikroTik - Debug"""

import httpx
import base64
import asyncio

async def test_simple():
    print("🔍 Test Connessione MikroTik Semplificato\n")
    
    # Configurazione
    router_ip = "185.203.24.2"
    port = 8728
    username = "admin"
    password = input(f"Password per {username}@{router_ip}: ")
    
    # Test 1: Connessione TCP base
    print(f"\n1️⃣ Test TCP porta {port}...")
    try:
        client = httpx.AsyncClient(timeout=5)
        response = await client.get(f"http://{router_ip}:{port}")
        print(f"   ✅ Porta {port} aperta e risponde")
        await client.aclose()
    except Exception as e:
        print(f"   ❌ Porta {port} non raggiungibile: {e}")
        return
    
    # Test 2: Endpoint REST /rest/system/identity
    print(f"\n2️⃣ Test endpoint REST /rest/system/identity...")
    try:
        auth = base64.b64encode(f"{username}:{password}".encode()).decode()
        headers = {
            "Authorization": f"Basic {auth}",
            "Content-Type": "application/json"
        }
        
        client = httpx.AsyncClient(timeout=10)
        url = f"http://{router_ip}:{port}/rest/system/identity"
        print(f"   URL: {url}")
        
        response = await client.get(url, headers=headers)
        print(f"   Status Code: {response.status_code}")
        print(f"   Headers: {dict(response.headers)}")
        
        if response.status_code == 200:
            print(f"   ✅ Autenticazione OK!")
            print(f"   Risposta: {response.text}")
        elif response.status_code == 401:
            print(f"   ❌ Credenziali errate (401 Unauthorized)")
        elif response.status_code == 404:
            print(f"   ❌ Endpoint non trovato (404) - API REST non abilitata?")
        else:
            print(f"   ⚠️  Status inaspettato: {response.status_code}")
            print(f"   Risposta: {response.text}")
        
        await client.aclose()
        
    except Exception as e:
        print(f"   ❌ Errore richiesta REST: {e}")
        import traceback
        traceback.print_exc()
        return
    
    # Test 3: Endpoint /rest/ip/firewall/address-list
    print(f"\n3️⃣ Test endpoint address-list...")
    try:
        client = httpx.AsyncClient(timeout=10)
        url = f"http://{router_ip}:{port}/rest/ip/firewall/address-list"
        
        response = await client.get(url, headers=headers)
        print(f"   Status Code: {response.status_code}")
        
        if response.status_code == 200:
            data = response.json()
            print(f"   ✅ Address-list leggibile!")
            print(f"   Totale entries: {len(data)}")
            if data:
                print(f"   Primo entry: {data[0]}")
        else:
            print(f"   ⚠️  Status: {response.status_code}")
            print(f"   Risposta: {response.text}")
        
        await client.aclose()
        
    except Exception as e:
        print(f"   ❌ Errore lettura address-list: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    print("="*60)
    asyncio.run(test_simple())
    print("\n" + "="*60)
