function detectIpVersion(ip){
    const ipv4Regex=/^(\d{1,3}\.){3}\d{1,3}(\/\d{1,2})?$/;
    const ipv6Regex=/^([0-9a-fA-F:]+)(\/\d{1,3})?$/;

    if(ipv4Regex.test(ip)){
        return"ipv4";
    }else if(ipv6Regex.test(ip)){
        return"ipv6";
    }else{
        return null;
    }
}

function highlightBGPOutput(text){
    text=text.replace(/\b215085\b/g,'<span class="asn215085-highlight">215085</span>');

    text=text.replace(/\b\d{4,6}\b/g,match=>{
        if(match==='215085')return match;
        return`<span class="asn-highlight">${match}</span>`;
    });

    text=text.split('\n').map(line=>{
        if(line.toLowerCase().includes('best')){
            return`<strong class="best-line">${line}</strong>`;
        }
        return line;
    }).join('\n');

    text=text.split('\n').map(line=>{
        if(line.toLowerCase().includes('table entry')){
            return`<strong class="best-line">${line}</strong>`;
        }
        return line;
    }).join('\n');

    text=text.split('\n').map(line=>{
        if(line.toLowerCase().includes('multipath')){
            return`<strong class="best-line">${line}</strong>`;
        }
        return line;
    }).join('\n');

    return text.replace(/\n/g,'<br>');
}

function displayBGPRoute(data){
    const outputElem=document.getElementById("bgpOutput");
    const rawText=data.data||JSON.stringify(data,null,2);
    const highlighted=highlightBGPOutput(rawText);
    outputElem.innerHTML=highlighted;
}

async function loadBGPRoute(){
    const outputElem=document.getElementById("bgpOutput");
    const prefix=document.getElementById("prefixInput").value.trim();

    if(!prefix){
        outputElem.textContent="Enter a valid prefix first.";
        return;
    }

    const ip_version=detectIpVersion(prefix);
    if(!ip_version){
        outputElem.textContent="Invalid IP address or prefix.";
        return;
    }

    outputElem.textContent="Loading...";

    const postData={
        ip_version:ip_version,
        bgprouteprefix:prefix
    };

    try{
        const response=await fetch("/bgp-route/lookup",{
            method:"POST",
            headers:{
                "Content-Type":"application/json",
            },
            body:JSON.stringify(postData),
        });
        if(!response.ok)throw new Error("Network response was not ok");
        const data=await response.json();

        if(data.error){
            outputElem.textContent="Error: "+data.error;
            return;
        }

        displayBGPRoute(data);
    }catch(error){
        outputElem.textContent="Error retrieving data: "+error.message;
    }
}
