#!/usr/bin/env sh
#
# lm-refactor - lang-aware code refactoring ollama local llm assistant
# dependencies: ollama | jq
#
# ---
# source: https://github.com/klen/dotfiles/blob/master/bin/lm-refactor

LLM=${LLM:-"$(ollama-current)"}

detect_language() {
  EXT="${1##*.}"
  case "${EXT}" in
    py) echo "Python" ;;
    js) echo "JavaScript" ;;
    ts) echo "TypeScript" ;;
    go) echo "Go" ;;
    rs) echo "Rust" ;;
    cpp | cc | cxx | c++) echo "C++" ;;
    c) echo "C" ;;
    sh | bash) echo "Bash" ;;
    java) echo "Java" ;;
    *) echo "code" ;;
  esac
}

refactor_file() {
  file="$1"

  if [ ! -f "${file}" ]; then
    echo "❌ File not found: ${file}"
    return 1
  fi

  language=$(detect_language "${file}")

  system="You are a ${language} code refactoring assistant.

Your job:
- Fix bugs and logic issues
- Optimize performance and memory usage
- Improve readability and apply clean code principles (DRY, KISS, SOLID, etc.)
- Refactor and simplify the code where possible

Output rules:
- Output only the final, modified version of the code
- Do NOT wrap the code in markdown blocks
- Do NOT add explanations, comments, or formatting
- Output raw code only — plain text, no prefixes or suffixes
"

  # content=$(<"$file")
  content=$(cat "${file}")

  prompt="Analyze and improve the following code. Output only the modified version, as plain code.

Code:

${content}"

  # shellcheck disable=SC2312
  raw_response=$(
    jq --null-input --compact-output --arg model "${LLM}" --arg prompt "${prompt}" \
      --arg system "${system}" \
      '{
          model: $model,
          messages: [
            { role: "system", content: $system },
            { role: "user", content: $prompt }
          ]
      }' \
      | curl -s http://localhost:1234/v1/chat/completions \
        -H "Content-Type: application/json" -d @-
  )

  if echo "${raw_response}" | jq --exit-status '.error' >/dev/null; then
    # shellcheck disable=SC2312
    echo "❌ LLM error for ${file}: $(echo "${raw_response}" | jq --raw-output '.error.message')" >&2
    return 1
  fi

  response=$(echo "${raw_response}" | jq --raw-output '.choices[0].message.content')

  if [ -z "${response}" ]; then
    echo "⚠️ No response from model for ${file}."
    return 1
  fi

  # remove ```lang and ``` blocks if present
  response=$(echo "${response}" | sed -e '/^```/d')

  echo "${response}" >"${file}"
  echo "✅ Refactored ${file}"
}

# === main logic ===
target="$1"

if [ -z "${target}" ]; then
  echo "Usage: $0 <file-or-directory>"
  exit 1
fi

if [ -d "${target}" ]; then
  # shellcheck disable=SC2312
  find "${target}" -type f \( -name "*.py" -o -name "*.js" -o -name "*.ts" -o -name "*.go" -o -name "*.rs" -o -name "*.c" -o -name "*.cpp" -o -name "*.sh" \) \
    | while read -r file; do
      refactor_file "${file}"
    done
else
  refactor_file "${target}"
fi
