#!/usr/bin/env python3

import re
import sys

def sanitize_resource_name(name):
    """Convert system name to valid Terraform resource identifier."""
    # Remove trailing spaces and convert to lowercase
    name = name.strip().lower()
    # Replace spaces and special chars with underscores
    name = re.sub(r'[^a-z0-9_]', '_', name)
    # Remove consecutive underscores
    name = re.sub(r'_+', '_', name)
    # Remove leading/trailing underscores
    name = name.strip('_')
    # Prefix with 'device_' if it starts with a number
    if name and name[0].isdigit():
        name = 'device_' + name
    return name

if len(sys.argv) < 3:
    print("Usage: ./generate_terraform.py <input_file> <site_name>")
    print("Example: ./generate_terraform.py new_hope_results.txt new_hope")
    sys.exit(1)

input_file = sys.argv[1]
site_name = sys.argv[2]
output_file = f"{site_name}_hosts.tf"

# Read SNMP results
with open(input_file, 'r') as f:
    devices = []
    for line in f:
        ip, sysname = line.strip().split('|')
        if sysname != 'UNKNOWN':
            resource_name = sanitize_resource_name(sysname)
            devices.append({
                'ip': ip,
                'name': sysname.strip(),
                'resource_name': resource_name
            })

# Handle duplicate resource names by appending IP last octet
seen_names = {}
for device in devices:
    original_name = device['resource_name']
    if original_name in seen_names:
        # Append the last octet of the IP to make it unique
        last_octet = device['ip'].split('.')[-1]
        device['resource_name'] = f"{original_name}_{last_octet}"
    else:
        seen_names[original_name] = True

# Generate Terraform file
with open(output_file, 'w') as f:
    for device in devices:
        f.write(f'resource "towerops_device" "{device["resource_name"]}" {{\n')
        f.write(f'  site_id      = towerops_site.{site_name}.id\n')
        f.write(f'  name         = "{device["name"]}"\n')
        f.write(f'  ip_address   = "{device["ip"]}"\n')
        f.write(f'  snmp_version = "1"\n')
        f.write(f'}}\n\n')

print(f"Generated {output_file} with {len(devices)} devices")
