#!/usr/bin/env python3
import requests
import json
import sys
import os

# Import from our existing app
from app.update_data import get_base_url

DEVICES_FILE = "devices.json"

def test_router(router):
    name = router["name"]
    host = router["host"]
    port = router["port"]
    user = router["user"]
    password = router["pass"]
    
    base_url = get_base_url(host, port)
    auth = (user, password)
    
    print(f"\n{'='*60}")
    print(f"TESTING ROUTER: {name} ({host})")
    print(f"{'='*60}")
    
    endpoints = ["system/identity", "system/resource", "interface"]
    
    for ep in endpoints:
        url = f"{base_url}/{ep}"
        print(f"\n📡 Requesting: {url}")
        
        try:
            response = requests.get(
                url, 
                auth=auth, 
                headers={"Accept": "application/json"},
                timeout=15
            )
            
            print(f"✅ Status Code: {response.status_code}")
            # print(f"Headers: {dict(response.headers)}")
            
            if response.status_code == 200:
                try:
                    data = response.json()
                    print(f"🟢 Success! Received {len(str(data))} bytes of JSON data.")
                    if isinstance(data, list) and len(data) > 0:
                        print(f"Sample data keys: {list(data[0].keys()) if isinstance(data[0], dict) else 'not a dict'}")
                except Exception as e:
                    print(f"🟡 Status 200 but JSON Parse Error: {e}")
                    print(f"Raw Content (First 200 chars): {response.text[:200]}")
            else:
                print(f"🔴 Failed with status {response.status_code}")
                print(f"Error Body: {response.text}")
                
        except requests.exceptions.ConnectTimeout:
            print("❌ Connection Timeout: Could not reach the router.")
        except requests.exceptions.ConnectionError as e:
            print(f"❌ Connection Error: {e}")
        except Exception as e:
            print(f"❌ Unexpected Error ({type(e).__name__}): {e}")

if __name__ == "__main__":
    if not os.path.exists(DEVICES_FILE):
        print(f"Error: {DEVICES_FILE} not found.")
        sys.exit(1)
        
    with open(DEVICES_FILE, 'r') as f:
        devices = json.load(f)
        
    if len(sys.argv) > 1:
        target = sys.argv[1].lower()
        devices = [d for d in devices if target in d["name"].lower() or target in d["host"]]
        if not devices:
            print(f"No router found matching '{target}'")
            sys.exit(1)

    for device in devices:
        test_router(device)
