import io
import urllib.request
import ipaddress

"""
Copyright (c) 2026. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its
   contributors may be used to endorse or promote products derived from
   this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING FROM, OUT OF OR IN
USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""

def find_hidden_gaps():
    target_url = "https://ftp.afrinic.net/stats/afrinic/delegated-afrinic-20250301"
    
    print(f"Fetching snapshot to analyze address layout: {target_url.split('/')[-1]}...\n")
    
    try:
        req = urllib.request.Request(target_url, headers={'User-Agent': 'Mozilla/5.0'})
        with urllib.request.urlopen(req) as response:
            raw_data = response.read().decode('utf-8', errors='ignore')
    except Exception as e:
        print(f"Network error fetching snapshot: {e}")
        return

    file_stream = io.StringIO(raw_data)
    allocated_intervals = []
    
    for line in file_stream:
        if line.startswith("#") or not line.strip():
            continue
            
        parts = line.split('|')
        if len(parts) >= 7:
            registry = parts[0]
            resource_type = parts[2]
            start_ip = parts[3]
            count = parts[4]
            
            # Focus strictly on IPv4 allocations
            if registry == 'afrinic' and resource_type == 'ipv4':
                try:
                    start_int = int(ipaddress.IPv4Address(start_ip))
                    num_ips = int(count)
                    end_int = start_int + num_ips - 1
                    allocated_intervals.append((start_int, end_int))
                except ValueError:
                    continue

    if not allocated_intervals:
        print("No active IPv4 blocks found to map gaps against.")
        return

    allocated_intervals.sort(key=lambda x: x[0])
    
    merged_intervals = [allocated_intervals[0]]
    for current in allocated_intervals[1:]:
        prev_start, prev_end = merged_intervals[-1]
        curr_start, curr_end = current
        
        if curr_start <= prev_end + 1:
            merged_intervals[-1] = (prev_start, max(prev_end, curr_end))
        else:
            merged_intervals.append(current)

    hidden_gaps = []
    for i in range(len(merged_intervals) - 1):
        gap_start_int = merged_intervals[i][1] + 1
        gap_end_int = merged_intervals[i+1][0] - 1
        
        if gap_start_int <= gap_end_int:
            gap_size = (gap_end_int - gap_start_int) + 1
            # We filter out tiny structural padding gaps (less than a /24 block size)
            if gap_size >= 256:
                hidden_gaps.append((gap_start_int, gap_end_int, gap_size))

    # Output hidden address gaps directly to the terminal
    print(f"--- GAP ANALYSIS COMPLETE ---")
    print(f"Identified {len(hidden_gaps)} unlisted/hidden structural gaps in the layout.\n")
    print("-" * 80)
    print(f"{'Gap Range Start':<16} | {'Gap Range End':<16} | {'Total Hidden IPs':<15} | {'Est. Size'}")
    print("-" * 80)
    
    for gap in hidden_gaps[:30]:  # Cap output to top 30 gaps for clean viewing
        start_str = str(ipaddress.IPv4Address(gap[0]))
        end_str = str(ipaddress.IPv4Address(gap[1]))
        size = gap[2]
        
        # Approximate the block size equivalent
        if size >= 65536:
            est_block = f"~/{24 - int(size/65536).bit_length()}" 
        else:
            est_block = f"~/{32 - size.bit_length() + 1}"
            
        print(f"{start_str:<16} | {end_str:<16} | {size:<15,} | {est_block}")
        
    print("-" * 80)
    if len(hidden_gaps) > 30:
        print(f"... List truncated. Total hidden footprint contains {sum(g[2] for g in hidden_gaps):,} IPs.")

if __name__ == "__main__":
    find_hidden_gaps()