#!/bin/bash

# Unified IP Tag Replacement
# Uses network_resources table and tag system
ipUpdateComposeTags()
{
    local app_name="$1"
    local full_file_path="$2"
    
    local ip_mapping_result=""
    if [[ "$LIBREPORTAL_RESET_NETWORK" != "1" ]]; then
        local sql="SELECT service_name, resource_value FROM network_resources WHERE app_name = '$app_name' AND resource_type = 'ip' AND status = 'active';"
        ip_mapping_result=$(sqlite3 "$docker_dir/$db_file" "$sql" 2>/dev/null)
    fi
    declare -A ip_mapping

    # Only process if we got results
    if [[ -n "$ip_mapping_result" ]]; then
        while IFS='|' read -r service_name resource_value; do
            # Skip empty service names
            if [[ -n "$service_name" && -n "$resource_value" ]]; then
                ip_mapping["$service_name"]="$resource_value"
            fi
        done <<< "$ip_mapping_result"
    else        
        # Get service names from SERVICE_TAG_N tags in docker-compose.yml
        local compose_services=()
        if [[ -f "$full_file_path" ]]; then
            # Extract service names from SERVICE_TAG_N tags
            for i in {1..20}; do
                local service_tag="SERVICE_TAG_$i"
                local compose_service=$(grep "#LIBREPORTAL|$service_tag|" "$full_file_path" | awk -F'|' '{print $3}' | head -1)
                if [[ -n "$compose_service" ]]; then
                    compose_services+=("$compose_service")
                fi
            done
        fi
        
        # If no service tags found, no services to process
        if [[ ${#compose_services[@]} -eq 0 ]]; then
            isNotice "No service tags found, skipping IP allocation"
        fi
        
        # Allocate IPs for each service
        service_counter=1
        first_allocated_ip=""  # Global variable for trusted domains processor
        for compose_service in "${compose_services[@]}"; do
            ipAllocation "$app_name" "$compose_service"
            local service_allocated_ip="$allocated_ip"  # Capture result immediately
            
            # Set global first allocated IP (for trusted domains processor)
            if [[ "$service_counter" -eq 1 && -n "$service_allocated_ip" ]]; then
                first_allocated_ip="$service_allocated_ip"
            fi
            
            if [[ -n "$service_allocated_ip" ]]; then
                ip_mapping["$compose_service"]="$service_allocated_ip"
            fi
            ((service_counter++))
        done
    fi

    # Walk SERVICE_TAG_N in numeric order so IP_TAG_i lines up with service i
    # deterministically (associative array key order is hash-random).
    local replaced_count=0
    for i in {1..20}; do
        local service_tag="SERVICE_TAG_$i"
        local compose_service
        compose_service=$(grep "#LIBREPORTAL|$service_tag|" "$full_file_path" 2>/dev/null \
            | awk -F'|' '{print $3}' | head -1)
        [[ -z "$compose_service" ]] && continue

        local allocated_ip="${ip_mapping[$compose_service]}"
        if [[ -n "$allocated_ip" ]]; then
            tagsManagerUpdateUniversalTag "$full_file_path" "IP_TAG_$i" "$allocated_ip"
            ((replaced_count++))
        else
            isNotice "No IP allocated for service: $compose_service (IP_TAG_$i)"
        fi
    done
    
    ip_update_result="Updated $replaced_count IP tag system"
    isSuccessful "$ip_update_result"
    
    # Cleanup IP-related variables for security and memory management
    unset compose_services
    unset ip_mapping
    unset ip_update_result
    unset ip_mapping_result
    unset resource_value
    unset service_name
    unset allocated_ip
    unset service_allocated_ip
    unset service_counter
}
