def parse_bgp_data(data):
    ipv4_section = ""
    ipv6_section = ""
    ipv4_info = {}
    ipv6_info = {}

    if "data" in data:
        raw_data = data["data"]

        ipv4_marker = "IPv4 Unicast Summary (VRF bgp):"
        ipv6_marker = "IPv6 Unicast Summary (VRF bgp):"

        ipv4_start = raw_data.find(ipv4_marker)
        ipv6_start = raw_data.find(ipv6_marker)

        if ipv4_start != -1:
            if ipv6_start != -1:
                ipv4_section = raw_data[ipv4_start + len(ipv4_marker):ipv6_start].strip()
            else:
                ipv4_section = raw_data[ipv4_start + len(ipv4_marker):].strip()
            ipv4_info = extract_bgp_info(ipv4_section)

        if ipv6_start != -1:
            ipv6_section = raw_data[ipv6_start + len(ipv6_marker):].strip()
            ipv6_info = extract_bgp_info(ipv6_section)

    def process_peers(peer_data):
        peers = []
        for line in peer_data.split("\n"):
            if line.strip().startswith("Neighbor"):
                continue
            if line.strip():
                peer_info = line.split()
                if len(peer_info) >= 12:
                    peers.append({
                        "neighbor": peer_info[0],
                        "version": peer_info[1],
                        "as_number": peer_info[2],
                        "msg_received": peer_info[3],
                        "msg_sent": peer_info[4],
                        "table_version": peer_info[5],
                        "in_queue": peer_info[6],
                        "out_queue": peer_info[7],
                        "up_down": peer_info[8],
                        "state_pfx_rcd": peer_info[9],
                        "prefix_sent": peer_info[10],
                        "description": " ".join(peer_info[11:])
                    })
        return peers

    ipv4_peers = process_peers(ipv4_section)
    ipv6_peers = process_peers(ipv6_section)

    return ipv4_info, ipv4_peers, ipv6_info, ipv6_peers

def extract_bgp_info(raw_data):
    lines = raw_data.split("\n")
    info = {}
    for line in lines:
        if "BGP router identifier" in line:
            parts = line.split(",")
            info["router_id"] = parts[0].split("identifier")[1].strip()
            info["local_as"] = parts[1].split("number")[1].strip().split(" ")[0]
            if "vrf-id" in parts[-1]:
                info["vrf_id"] = parts[-1].split("vrf-id")[1].strip()
        if "BGP table version" in line:
            info["table_version"] = line.split("version")[1].strip()
        if "RIB entries" in line:
            parts = line.split(",")
            info["rib_entries"] = parts[0].split("entries")[1].strip()
            info["rib_memory"] = parts[1].split("using")[1].strip()
        if "Peers" in line:
            parts = line.split(",")
            info["peers"] = parts[0].split("Peers")[1].strip()
            info["peers_memory"] = parts[1].split("using")[1].strip()
    return info
    
def generate_bgp_json(ipv4_info, ipv4_peers, ipv6_info, ipv6_peers, bfd_peers=None):
    if bfd_peers is None:
        bfd_peers = []
        
    return {
        "ipv4_info": ipv4_info,
        "ipv4_peers": ipv4_peers,
        "ipv6_info": ipv6_info,
        "ipv6_peers": ipv6_peers,
        "bfd_peers": list(bfd_peers)
    }

def parse_route_summary(raw_data):
    summary = {"routes": 0, "fib": 0}
    try:
        if "data" in raw_data and raw_data["data"]:
            lines = raw_data["data"].split('\n')
            for line in lines:
                if line.strip().lower().startswith('totals'):
                    parts = line.split()
                    if len(parts) >= 2 and parts[1].isdigit():
                        summary["routes"] = int(parts[1])
                    if len(parts) >= 3 and parts[2].isdigit():
                        summary["fib"] = int(parts[2])
                    break 
    except Exception as e:
        print(f"[WARN] Error parsing route summary: {e}")
        return {"routes": 0, "fib": 0}
    return summary