import sys
import logging
from variables import DEBUG_LEVEL
import csv
# Use getattr() to dynamically access the logging level
log_level = getattr(logging,DEBUG_LEVEL, logging.INFO)  # Default to logging.INFO if not found

# Set up logging for the main script
logging.basicConfig(
    format='%(asctime)s - %(levelname)s - %(message)s',
    level=log_level,
    handlers=[logging.StreamHandler()]  # Logs to console by default
)

def generate_nodes_info_csv(path_csv_file: str, nodes: list):
    """
    Function to generate a CSV file with node information.
    
    Arguments:
    - path_csv_file: Path to the CSV file to create
    - nodes_list: List of node names (first node is server, then alternate between defender and attacker)
    """
    
    # Convert nodes to a list if it's a string
    if isinstance(nodes, str):
        nodes_list = nodes.split()
    elif isinstance(nodes, list):
        nodes_list = nodes
    else:
        raise ValueError("Nodes should be a string or a list of node names.")

    nodes_info = {}

    # Assign types dynamically: first node is server, then alternate between defender and attacker
    for i, node in enumerate(nodes_list):
        if i == 0:
            node_type = "server"  # First node is server
        elif i % 2 == 1:
            node_type = "defender"  # Alternate between defender and attacker
        else:
            node_type = "attacker"
        nodes_info[node] = {"type": node_type}

    # Columns for CSV
    columns = ["Node", "Type"]

    try:
        # Write to CSV
        with open(path_csv_file, mode='w', newline='') as file:
            writer = csv.writer(file)
            writer.writerow(columns)  # Write header
            for node, info in nodes_info.items():
                writer.writerow([node, info["type"]])

        logging.info(f"CSV file '{path_csv_file}' created with node information.")
    
    except Exception as e:
        logging.error(f"Error while creating CSV file: {e}")



if __name__ == "__main__":
    # Check for correct usage
    if len(sys.argv) < 3:
        logging.error("Usage: python generate_nodes_info.py <csv_file_path> <node1> <node2> ...")
        sys.exit(1)

    # Get arguments from command line
    csv_file_path = sys.argv[1]
    nodes_list = sys.argv[2:]

    # Log the arguments received
    logging.info(f"Generating CSV for the following nodes: {nodes_list}")
    
    # Call the function from utils.py to generate the CSV
    generate_nodes_info_csv(csv_file_path, nodes_list)
