filename="/usr/local/bin/meta-pipeline.sh"

conf_print_meta_pipeline_sh() {
	cat <<-'EOF'
		#!/usr/bin/env bash
		# Meta Pipeline with --target support

		set -euo pipefail

		# ----- DEFAULTS -----
		WORKSPACE_DIR="${WORKSPACE_DIR:-$HOME/staging_area}"
		TARGET="dev"

		# ----- ARG PARSING -----
		FILE=""

		while [ $# -gt 0 ]; do
			case "$1" in
				--target)
					TARGET="$2"
					shift 2
					;;
				--target=*)
					TARGET="${1#*=}"
					shift
					;;
				-*)
					echo "[ERROR] Unknown flag: $1"
					exit 1
					;;
				*)
					FILE="$1"
					shift
					;;
			esac
		done

		if [ -z "$FILE" ]; then
			cat <<USAGE
			Usage: $(basename "$0") [--target <name>] <file.md>

			Defaults:
			  WORKSPACE_DIR=$WORKSPACE_DIR
			  TARGET=$TARGET

			Override:
			  BUILD_DIR takes precedence if set
			USAGE
			exit 1
		fi

		# ----- BUILD_DIR RESOLUTION -----
		if [ -z "${BUILD_DIR+x}" ]; then
			BUILD_DIR="${WORKSPACE_DIR}/${TARGET}"
		fi

		cat <<INFO
		[INFO] Workspace : $WORKSPACE_DIR
		[INFO] Target    : $TARGET
		[INFO] Build Dir : $BUILD_DIR
		INFO

		# ----- PIPELINE -----

		cat <<STEP
		[STEP 1] Validation
		STEP
		md-validate.sh "$FILE"

		cat <<STEP
		[STEP 2] Conversion
		STEP
		md-to-sh.sh "$FILE"

		OUT="${FILE%.md}.sh"

		cat <<STEP
		[STEP 3] Execution
		STEP

		BUILD_DIR="$BUILD_DIR" bash "$OUT"

		cat <<DONE
		[COMPLETE] Pipeline finished
		Staged output: $BUILD_DIR
		DONE
	EOF
}

mkdir -p "$(dirname "${BUILD_DIR}${filename}")"
conf_print_meta_pipeline_sh | tee "${BUILD_DIR}${filename}" > /dev/null
chmod +x "${BUILD_DIR}${filename}"
