#!/usr/bin/env bash

declare -a INCLUDE_STACK

process_file() {
    local file_path="$1"

    if [[ ! -f "$file_path" ]]; then
        echo "Error: File '$file_path' not found." >&2
        exit 1
    fi

    for included_file in "${INCLUDE_STACK[@]}"; do
        if [[ "$included_file" == "$file_path" ]]; then
            echo "Error: Circular dependency detected!" >&2
            echo "Include stack: ${INCLUDE_STACK[*]} -> $file_path" >&2
            exit 1
        fi
    done

    INCLUDE_STACK+=("$file_path")

    while IFS= read -r line || [[ -n "$line" ]]; do
        if [[ "$line" =~ ^[[:space:]]*--[[:space:]]*#include[[:space:]]+\"(.*)\"[[:space:]]*$ ]]; then
            local target_file="${BASH_REMATCH[1]}"
            process_file "$(dirname "$file_path")/$target_file"
        else
            printf '%s\n' "$line"
        fi
    done < "$file_path"

    unset 'INCLUDE_STACK[-1]'
}

while getopts "i:o:" opt; do
    case $opt in
        i) INPUT_FILE="$OPTARG" ;;
        o) OUTPUT_FILE="$OPTARG" ;;
        \?) echo "Invalid option: -$OPTARG" >&2; exit 1 ;;
    esac
done

if [[ -z "$INPUT_FILE" || -z "$OUTPUT_FILE" ]]; then
    echo "Usage: $0 -i <input_file> -o <output_file>"
    exit 1
fi

: > "$OUTPUT_FILE"

echo "Building project: $INPUT_FILE -> $OUTPUT_FILE ..."
process_file "$INPUT_FILE" >> "$OUTPUT_FILE"