#!/usr/bin/env bash
# General-purpose string utilities for shellops.

import "$SHELLOPS_DIR/lib/json.api.sh"

# ── Predicates ────────────────────────────────────────────────────────

:<<'DOC'
Returns 0 if text contains the given substring, 1 otherwise.

Usage: string_contains "$text" "$substring"
DOC
function string_contains() {
  [[ "$1" == *"$2"* ]]
}

:<<'DOC'
Returns 0 if text starts with the given prefix, 1 otherwise.

Usage: string_starts_with "$text" "$prefix"
DOC
function string_starts_with() {
  [[ "$1" == "$2"* ]]
}

:<<'DOC'
Returns 0 if text ends with the given suffix, 1 otherwise.

Usage: string_ends_with "$text" "$suffix"
DOC
function string_ends_with() {
  [[ "$1" == *"$2" ]]
}

# ── Substitution ──────────────────────────────────────────────────────

:<<'DOC'
Replaces every occurrence of a literal marker with a plain string.
Markers are exact substrings, not patterns.

Usage: string_replace "$text" "$marker" "$replacement"
DOC
function string_replace() {
  local text="$1" marker="$2" replacement="$3"
  string_replace_json "$text" "$marker" "$(jq_encode_string "$replacement")"
}

:<<'DOC'
Replaces every occurrence of a literal marker with a JSON value. JSON strings
are inserted as raw text; structured values (objects, arrays, numbers, booleans,
null) are serialized to compact JSON first.

Usage: string_replace_json "$text" "$marker" "$value_json"
DOC
function string_replace_json() {
  local text="$1" marker="$2" value_json="$3"

  if [[ -z "$marker" ]]; then
    fatal "string_replace_json: marker must be non-empty"
    return 1
  fi

  if ! jq_is_valid "$value_json"; then
    fatal "string_replace_json: value must be valid JSON"
    return 1
  fi

  jq -rn \
    --arg cur "$text" \
    --arg m "$marker" \
    --argjson v "$value_json" \
    '($v | if type == "string" then . else tojson end) as $t
     | ($cur | split($m) | join($t))'
}

:<<'DOC'
Reads a file and applies one marker substitution (same rules as
string_replace_json). Writes the result to stdout.

Usage: string_replace_file "$path" "$marker" "$value_json"
DOC
function string_replace_file() {
  local path="$1" marker="$2" value_json="$3"

  if [[ ! -f "$path" ]]; then
    fatal "string_replace_file: file not found: $path"
    return 1
  fi

  string_replace_json "$(cat "$path")" "$marker" "$value_json"
}
