import boto3
import os
import time
from datetime import datetime
import sys

# Define your AWS region and credentials
aws_region = os.getenv('AWS_NLB_REGION')
nlb_subnet = os.getenv('NLB_SUBNET_ID')
nlb_name = os.getenv('NLB_NAME', 'hsm-nlb')
lb_scheme = os.getenv('LB_SCHEME', 'internet-facing')
lb_vpc = os.getenv('LB_VPC_ID')
hsm_ip = os.getenv('HSM_IP')
sg_id = os.getenv('SG_ID')
github_env_path = os.getenv('GITHUB_ENV')
zone_id = "Z9DC2VSSE1HT0"
record_name = "hsm-sign.safersoftware.net"
target_hosted_zone_id = "Z2IFOLAFXWLO4F"

def update_route53_record(zone_id, record_name, nlb_dns, target_hosted_zone_id):
    client = boto3.client('route53')

    changes = [{
        'Action': 'UPSERT',
        'ResourceRecordSet': {
            'Name': record_name,
            'Type': 'A',
            'AliasTarget': {
                'DNSName': nlb_dns,
                'HostedZoneId': target_hosted_zone_id,
                'EvaluateTargetHealth': False
            }
        }
    }]

    response = client.change_resource_record_sets(
        HostedZoneId=zone_id,
        ChangeBatch={
            'Changes': changes
        }
    )

    print(f"Route 53 record updated. Change ID: {response['ChangeInfo']['Id']}")
    print(f"Record {record_name} is pointing to {nlb_dns}")

# Create a boto3 NLB client
elbv2 = boto3.client('elbv2', region_name=aws_region)

#Check if NLB already exists
try:
    existing_nlb = elbv2.describe_load_balancers(Names=[nlb_name])
    if existing_nlb['LoadBalancers']:
        print(f"NLB with name '{nlb_name}' already exists. Stopping further execution.")
        sys.exit()
except:
    # Create the NLB
    nlb_response = elbv2.create_load_balancer(
        Name=nlb_name,
        Subnets=[nlb_subnet],  # Replace with your subnet IDs
        Scheme=lb_scheme,  # Use 'internal' for an internal NLB
        SecurityGroups=[sg_id],
        Tags=[
            {
                'Key': 'Environment',
                'Value': 'Agents'
            },
            {
                'Key': 'department',
                'Value': 'Devops'
            },
        ],
        Type='network'
    )
    with open(github_env_path, 'a') as file:
        file.write(f"""NLB_CREATED=true\n""")

    # Create three target groups
    target_group_ports = [2223, 2224, 2225]

    for target_group_port in target_group_ports:
        target_group_response = elbv2.create_target_group(
            Name=f"hsm-target-{target_group_port}",
            Protocol='TCP',
            Port=target_group_port,  # Replace with your desired port
            VpcId=lb_vpc,  # Replace with your VPC ID
            TargetType='ip',  # Use 'ip' for IP addresses or 'lambda' for AWS Lambda functions
            Tags=[
                {
                    'Key': 'Environment',
                    'Value': 'Agents'
                },
                {
                    'Key': 'department',
                    'Value': 'Devops'
                },
            ]
        )

        # Add targets to each target group (replace 'targets' with your target instances)
        target_group_arn = target_group_response['TargetGroups'][0]['TargetGroupArn']
        targets = [
            {
                'Id': hsm_ip,  # Replace with the ID of your first target instance
                'Port': target_group_port  # Replace with the port your instance listens on
            }
        ]
        elbv2.register_targets(TargetGroupArn=target_group_arn, Targets=targets)

    # Attach target groups to the NLB
    for target_group_port in target_group_ports:
        elbv2.create_listener(
            DefaultActions=[
                {
                    'TargetGroupArn': elbv2.describe_target_groups(
                        Names=[f"hsm-target-{target_group_port}"]
                    )['TargetGroups'][0]['TargetGroupArn'],
                    'Type': 'forward',
                },
            ],
            LoadBalancerArn=nlb_response['LoadBalancers'][0]['LoadBalancerArn'],
            Port=target_group_port,
            Protocol='TCP',
        )

    print(f'NLB with name {nlb_name} and target groups created successfully.')

    stop_wait = False
    count = 0
    while not stop_wait:
        nlb_response = elbv2.describe_load_balancers(Names=[nlb_name])
        nlb_status = nlb_response['LoadBalancers'][0]['State']['Code']
        if nlb_status == 'active':
            print("lb in status active. done")
            nlb_dns = nlb_response['LoadBalancers'][0]["DNSName"]
            with open(github_env_path, 'a') as file:
                file.write(f"""NLB_DNS={nlb_dns}\n""")
            print(nlb_dns)
            break
        print(f"{count}. {datetime.now()} lb in status - {nlb_status}. sleep 5")
        sys.stdout.flush()
        time.sleep(5)
        count += 1
        if count == 60:
            stop_wait = True
            print("ERROR - the nlb did not get to active status")

    update_route53_record(zone_id, record_name, nlb_dns, target_hosted_zone_id)
