#!/usr/bin/env python3
"""
Check IP availability in range 192.168.11.28-99
Excludes reserved range (192.168.11.10-25) and already-assigned static IPs
"""

import re
from datetime import datetime

# Reserved range for physical servers
RESERVED_START = 10
RESERVED_END = 25

# Starting IP for new assignments
START_IP = 28
END_IP = 99

# Get latest inventory
import glob
import os

inventory_files = sorted(glob.glob("/home/intlc/projects/proxmox/CONTAINER_INVENTORY_*.md"), reverse=True)
if not inventory_files:
    print("Error: No inventory file found. Run scan-all-containers.py first.")
    exit(1)

inventory_file = inventory_files[0]
print(f"Using inventory: {inventory_file}\n")

# Read inventory and extract all used IPs
used_ips = set()
reserved_ips = set(range(RESERVED_START, RESERVED_END + 1))

with open(inventory_file, 'r') as f:
    for line in f:
        # Match IP addresses in the table
        # Format: | VMID | Name | Host | Status | IP Config | Current IP | Hostname |
        if '|' in line and '192.168.11' in line:
            # Extract IP from "Current IP" column (6th column)
            parts = [p.strip() for p in line.split('|')]
            if len(parts) >= 7:
                current_ip = parts[6].strip()
                if current_ip and current_ip != 'N/A' and current_ip.startswith('192.168.11.'):
                    ip_num = int(current_ip.split('.')[-1])
                    used_ips.add(ip_num)
                
                # Also check IP Config column (5th column)
                ip_config = parts[5].strip()
                if ip_config and ip_config != 'N/A' and ip_config != 'dhcp' and ip_config != 'auto':
                    # Extract IP from config like "192.168.11.100/24"
                    ip_match = re.search(r'192\.168\.11\.(\d+)', ip_config)
                    if ip_match:
                        ip_num = int(ip_match.group(1))
                        used_ips.add(ip_num)

# Also check for IPs in reserved range that are used
reserved_used = used_ips & reserved_ips

# Find available IPs
available_ips = []
for ip_num in range(START_IP, END_IP + 1):
    if ip_num not in used_ips and ip_num not in reserved_ips:
        available_ips.append(ip_num)

# Output results
output_file = f"/home/intlc/projects/proxmox/IP_AVAILABILITY_{datetime.now().strftime('%Y%m%d_%H%M%S')}.md"

with open(output_file, 'w') as f:
    f.write(f"""# IP Availability Check

**Generated**: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
**Source**: {inventory_file}

---

## IP Range Analysis

- **Reserved Range**: 192.168.11.{RESERVED_START}-{RESERVED_END} (Physical servers)
- **Available Range**: 192.168.11.{START_IP}-{END_IP}
- **Total IPs in Available Range**: {END_IP - START_IP + 1}

---

## Used IPs

### Static IPs in Available Range ({START_IP}-{END_IP})
""")
    
    static_in_range = sorted([ip for ip in used_ips if START_IP <= ip <= END_IP])
    if static_in_range:
        for ip_num in static_in_range:
            f.write(f"- 192.168.11.{ip_num}\n")
    else:
        f.write("- None\n")
    
    f.write(f"""
### Reserved IPs Currently Used by Containers
""")
    
    if reserved_used:
        for ip_num in sorted(reserved_used):
            f.write(f"- 192.168.11.{ip_num} ⚠️ **CONFLICT** (in reserved range)\n")
    else:
        f.write("- None\n")
    
    f.write(f"""
---

## Available IPs

**Total Available**: {len(available_ips)} IPs

### First 20 Available IPs (for DHCP conversion)
""")
    
    for ip_num in available_ips[:20]:
        f.write(f"- 192.168.11.{ip_num}\n")
    
    if len(available_ips) > 20:
        f.write(f"\n... and {len(available_ips) - 20} more\n")
    
    f.write(f"""
---

## Summary

- **Used IPs in range {START_IP}-{END_IP}**: {len(static_in_range)}
- **Available IPs**: {len(available_ips)}
- **Reserved IPs used by containers**: {len(reserved_used)} ⚠️

---

## Recommendation

Starting from **192.168.11.{available_ips[0] if available_ips else START_IP}** for DHCP to static IP conversion.

**Note**: {len(reserved_used)} container(s) are using IPs in the reserved range and should be moved first.
""")

print(f"=== IP Availability Check ===")
print(f"\nReserved range (physical servers): 192.168.11.{RESERVED_START}-{RESERVED_END}")
print(f"Available range: 192.168.11.{START_IP}-{END_IP}")
print(f"\nUsed IPs in available range: {len(static_in_range)}")
print(f"Available IPs: {len(available_ips)}")
print(f"Reserved IPs used by containers: {len(reserved_used)}")
if reserved_used:
    print(f"  ⚠️  IPs: {', '.join([f'192.168.11.{ip}' for ip in sorted(reserved_used)])}")
print(f"\nFirst 10 available IPs:")
for ip_num in available_ips[:10]:
    print(f"  - 192.168.11.{ip_num}")
print(f"\nOutput file: {output_file}")
