#!/bin/bash

# ANSI color codes
GREEN='\033[0;32m'
RED='\033[0;31m'
GRAY='\033[0;90m'
NC='\033[0m' # No Color

# Check if input file is provided
if [ $# -ne 1 ]; then
    echo -e "${RED}Usage: $0 <input_file>${NC}"
    exit 1
fi

input_file="$1"

# Check if input file exists
if [ ! -f "$input_file" ]; then
    echo -e "${RED}Error: File '$input_file' not found${NC}"
    exit 1
fi

changes_made=0

# Process each line
while IFS=':' read -r file_path line_err status desc data; do
    # Trim whitespace from all parts (both leading and trailing)
    file_path=$(echo "$file_path" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
    line_err=$(echo "$line_err" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
    status=$(echo "$status" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
    desc=$(echo "$desc" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
    data=$(echo "$data" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')

    echo -e "${GRAY}DEBUG: Processing line:${NC}"
    echo -e "${GRAY}DEBUG: file_path=[$file_path]${NC}"
    echo -e "${GRAY}DEBUG: line_err=[$line_err]${NC}"
    echo -e "${GRAY}DEBUG: status=[$status]${NC}"
    echo -e "${GRAY}DEBUG: desc=[$desc]${NC}"
    echo -e "${GRAY}DEBUG: data=[$data]${NC}"

    # Check if file exists and description matches conditions
    if [ -f "$file_path" ]; then
        echo -e "${GRAY}DEBUG: File exists: $file_path${NC}"
        
        if [ "$desc" = "undefined label" ]; then
            echo -e "${GRAY}DEBUG: Found 'undefined label' case${NC}"
            # Check if data is enclosed in < and >
            if [[ "$data" =~ ^\<.*\>$ ]]; then
                # Remove < and > for processing
                clean_data=$(echo "$data" | sed 's/^<//;s/>$//')
                # Replace \, /, or _ with - in clean_data
                new_data=$(echo "$clean_data" | tr '\\/_' '-')
                echo -e "${GRAY}DEBUG: Changing '$data' to '<$new_data>'${NC}"

                # Check if the data appears in an {image} directive
                if grep -B1 "$data" "$file_path" | grep -q "{image}"; then
                    echo -e "${GRAY}DEBUG: Skipping '$data' as it appears in an {image} directive${NC}"
                else
                    # Replace the old data with new data in the file, only if not preceded by {image}
                    if sed -i "/{image}/!s|$data|<$new_data>|g" "$file_path" 2>/dev/null; then
                        changes_made=$((changes_made + 1))
                        echo -e "${GREEN}Processed: $file_path - Changed '$data' to '<$new_data>'${NC}"
                    else
                        echo -e "${RED}WARNING: Failed to modify $file_path${NC}"
                    fi
                fi
            else
                echo -e "${GRAY}DEBUG: Skipping '$data' as it is not enclosed in <>${NC}"
            fi

        elif [[ "$desc" =~ "toctree contains reference to nonexisting document" ]]; then
            echo -e "${GRAY}DEBUG: Found 'toctree' case${NC}"
            # Extract the document reference from data (assuming it's in single quotes)
            doc_ref=$(echo "$data" | grep -o "'[^']*'" | tr -d "'")
            if [ -n "$doc_ref" ]; then
                # Replace \, /, or _ with - in doc_ref
                new_data=$(echo "$doc_ref" | tr '\\/_' '-')
                echo -e "${GRAY}DEBUG: Changing '$doc_ref' to '$new_data'${NC}"

                # Check if the doc_ref appears in an {image} directive
                if grep -B1 "$doc_ref" "$file_path" | grep -q "{image}"; then
                    echo -e "${GRAY}DEBUG: Skipping '$doc_ref' as it appears in an {image} directive${NC}"
                else
                    # Replace the old data with new data in the file, only if not preceded by {image}
                    if sed -i "/{image}/!s|$doc_ref|$new_data|g" "$file_path" 2>/dev/null; then
                        changes_made=$((changes_made + 1))
                        echo -e "${GREEN}Processed: $file_path - Changed '$doc_ref' to '$new_data'${NC}"
                    else
                        echo -e "${RED}WARNING: Failed to modify $file_path${NC}"
                    fi
                fi
            else
                echo -e "${RED}WARNING: Could not extract document reference from '$data' in $file_path${NC}"
            fi

        elif [[ "$desc" =~ "card directive targets nonexisting document" ]]; then
            echo -e "${GRAY}DEBUG: Found 'card directive' case${NC}"
            # Extract the document reference from desc (since data is empty), remove .rst
            doc_ref=$(echo "$desc" | grep -o "'[^']*'" | tr -d "'" | sed 's/\.rst$//')
            if [ -n "$doc_ref" ]; then
                # Replace \, /, or _ with - in doc_ref
                new_data=$(echo "$doc_ref" | tr '\\/_' '-')
                echo -e "${GRAY}DEBUG: Changing '$doc_ref' to '$new_data'${NC}"

                # Check if the doc_ref appears in an {image} directive
                if grep -B1 "$doc_ref" "$file_path" | grep -q "{image}"; then
                    echo -e "${GRAY}DEBUG: Skipping '$doc_ref' as it appears in an {image} directive${NC}"
                else
                    # Replace the old data with new data in the file, only if not preceded by {image}
                    if sed -i "/{image}/!s|$doc_ref|$new_data|g" "$file_path" 2>/dev/null; then
                        changes_made=$((changes_made + 1))
                        echo -e "${GREEN}Processed: $file_path - Changed '$doc_ref' to '$new_data'${NC}"
                    else
                        echo -e "${RED}WARNING: Failed to modify $file_path${NC}"
                    fi
                fi
            else
                echo -e "${RED}WARNING: Could not extract document reference from '$desc' in $file_path${NC}"
            fi

        else
            echo -e "${GRAY}DEBUG: Description '$desc' doesn't match any conditions${NC}"
        fi
    else
        echo -e "${RED}WARNING: File not found: $file_path${NC}"
    fi
    echo -e "${GRAY}DEBUG: ---${NC}"

done < "$input_file"

echo -e "${GREEN}Processing completed!${NC}"
echo -e "${GREEN}Total changes made: $changes_made${NC}"