#!/usr/bin/env python3

import ssl
from librouteros import connect
from librouteros.query import Key

def get_climax_router_data():
    """Connect to Climax router and retrieve network configuration"""
    
    # Router connection details
    router_ip = '10.254.254.102'
    username = 'grahamro'
    password = 'cFKhz8q5gPLoucMbcT1Iy58r3IXgc3'
    
    print(f"=== Connecting to Climax Router ({router_ip}) ===\n")
    
    # SSL context for secure connection
    ctx = ssl.create_default_context()
    ctx.check_hostname = False
    ctx.verify_mode = ssl.CERT_NONE
    
    try:
        # Connect to router
        api = connect(
            username=username,
            password=password,
            host=router_ip,
            port=8729,
            ssl_wrapper=ctx.wrap_socket
        )
        
        print("✓ Connected successfully\n")
        
        # Get IP addresses
        print("=== IP Addresses ===")
        ip_addresses = api('/ip/address/print')
        
        subnets = []
        for addr in ip_addresses:
            if not addr.get('disabled', False):
                address = addr['address']
                interface = addr.get('interface', 'unknown')
                network = addr.get('network', '')
                comment = addr.get('comment', '')
                
                print(f"Interface: {interface}")
                print(f"  Address: {address}")
                print(f"  Network: {network}")
                if comment:
                    print(f"  Comment: {comment}")
                print()
                
                subnets.append({
                    'address': address,
                    'network': network,
                    'interface': interface,
                    'comment': comment
                })
        
        # Get PPPoE servers
        print("\n=== PPPoE Servers ===")
        try:
            pppoe_servers = api('/interface/pppoe-server/server/print')
            for server in pppoe_servers:
                if not server.get('disabled', False):
                    name = server.get('service-name', 'unnamed')
                    interface = server.get('interface', 'unknown')
                    print(f"Service: {name} on {interface}")
        except:
            print("No PPPoE servers found or access denied")
        
        # Get interfaces
        print("\n=== Active Interfaces ===")
        interfaces = api('/interface/print')
        active_interfaces = []
        
        for iface in interfaces:
            if not iface.get('disabled', False) and iface.get('running', False):
                name = iface['name']
                itype = iface.get('type', 'unknown')
                mac = iface.get('mac-address', 'N/A')
                comment = iface.get('comment', '')
                
                active_interfaces.append({
                    'name': name,
                    'type': itype,
                    'mac': mac,
                    'comment': comment
                })
                
                print(f"{name} ({itype})")
                if comment:
                    print(f"  Comment: {comment}")
        
        # Close connection
        api.close()
        
        print(f"\n=== Summary ===")
        print(f"Found {len(subnets)} IP addresses/subnets")
        print(f"Found {len(active_interfaces)} active interfaces")
        
        # Return data for further processing
        return {
            'subnets': subnets,
            'interfaces': active_interfaces,
            'router_ip': router_ip
        }
        
    except Exception as e:
        print(f"✗ Connection failed: {e}")
        return None


def main():
    data = get_climax_router_data()
    
    if data:
        print("\n=== Router Data Retrieved Successfully ===")
        print(f"This data can be used to update NetBox with Climax router configuration")
    else:
        print("\n✗ Failed to retrieve router data")


if __name__ == "__main__":
    main()