#!/usr/bin/env bash
# get-config.sh — Fetch the latest project settings from the Dark Flow Web UI
# and refresh the local .darkflow cache + .darkflow.d/routines.yml.
#
# Called automatically by darkflow-run.sh before each routine, and prepended to
# every slash command's "Step 1 — Read project config".
#
# Safe to run at any time: silently no-ops if the server is offline or unreachable.
# Identity is via repoUrl (the DB unique key); webapp_url is the local anchor.

set -euo pipefail

# ── Paths ─────────────────────────────────────────────────────────────────────
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
DARKFLOW_CFG="${PROJECT_ROOT}/.darkflow"
ROUTINES_YML="${SCRIPT_DIR}/routines.yml"

# ── Helpers ───────────────────────────────────────────────────────────────────
_val() {
  local key="$1" default="${2:-}"
  if [[ -f "$DARKFLOW_CFG" ]]; then
    local v; v=$(grep -E "^${key}=" "$DARKFLOW_CFG" 2>/dev/null | head -1 | cut -d= -f2-)
    [[ -n "$v" ]] && { echo "$v"; return; }
  fi
  echo "$default"
}

_set_val() {
  local key="$1" value="$2"
  if grep -q "^${key}=" "$DARKFLOW_CFG" 2>/dev/null; then
    if [[ "$(uname)" == "Darwin" ]]; then
      sed -i '' "s|^${key}=.*|${key}=${value}|" "$DARKFLOW_CFG"
    else
      sed -i "s|^${key}=.*|${key}=${value}|" "$DARKFLOW_CFG"
    fi
  else
    echo "${key}=${value}" >> "$DARKFLOW_CFG"
  fi
}

# ── Prerequisites ─────────────────────────────────────────────────────────────
[[ -f "$DARKFLOW_CFG" ]] || exit 0          # no local config at all — skip
command -v curl &>/dev/null || exit 0       # no curl — skip

webapp_url=$(_val "webapp_url" "")
[[ -n "$webapp_url" ]] || exit 0            # no webapp_url — skip

# ── Resolve repoUrl ───────────────────────────────────────────────────────────
cd "$PROJECT_ROOT" 2>/dev/null || exit 0
if ! command -v gh &>/dev/null; then exit 0; fi
repo_url=$(gh repo view --json url -q .url 2>/dev/null || echo "")
[[ -n "$repo_url" ]] || exit 0

# ── Fetch settings from webapp ────────────────────────────────────────────────
encoded_url=$(python3 -c "import urllib.parse; print(urllib.parse.quote('${repo_url}', safe=''))" 2>/dev/null \
  || printf '%s' "$repo_url" | sed 's|:|%3A|g; s|/|%2F|g')

response=$(curl -fsS --max-time 5 \
  "${webapp_url}/api/projects/by-repo?repoUrl=${encoded_url}" 2>/dev/null) || exit 0

# Validate it looks like JSON
[[ "${response:0:1}" == "{" ]] || exit 0

# ── Parse and update .darkflow ────────────────────────────────────────────────
_jq() {
  local field="$1"
  if command -v jq &>/dev/null; then
    echo "$response" | jq -r "${field} // empty" 2>/dev/null
  else
    # Minimal grep/sed fallback for environments without jq
    echo "$response" | grep -oP "\"${field#.}\":\s*\"[^\"]*\"" | head -1 | sed 's/.*": *"\(.*\)"/\1/'
  fi
}

name=$(_jq '.name');            [[ -n "$name" ]]            && _set_val "name"             "$name"
slug=$(_jq '.slug');            [[ -n "$slug" ]]            && _set_val "slug"             "$slug"
branch=$(_jq '.branch');        [[ -n "$branch" ]]          && _set_val "branch"           "$branch"
language=$(_jq '.language');    [[ -n "$language" ]]        && _set_val "language"         "$language"
merge=$(_jq '.mergeStrategy');  [[ -n "$merge" ]]           && _set_val "merge_strategy"   "$merge"
phid=$(_jq '.posthogProjectId');[[ -n "$phid" ]]            && _set_val "posthog_project_id" "$phid"
obs_tool=$(_jq '.obsTool');     [[ -n "$obs_tool" ]]        && _set_val "obs_tool"         "$obs_tool"
obs_url=$(_jq '.obsUrl');       [[ -n "$obs_url" ]]         && _set_val "obs_url"          "$obs_url"

if command -v jq &>/dev/null; then
  max_con=$(echo "$response" | jq -r '.maxConcurrent // empty' 2>/dev/null)
  [[ -n "$max_con" ]] && _set_val "max_concurrent" "$max_con"
fi

# ── Regenerate routines.yml from the settings response ────────────────────────
if command -v jq &>/dev/null; then
  routines_json=$(echo "$response" | jq -c '.routines // []' 2>/dev/null)
  routine_count=$(echo "$routines_json" | jq 'length' 2>/dev/null || echo "0")

  if [[ "$routine_count" -gt "0" ]]; then
    {
      echo "# .darkflow.d/routines.yml — auto-generated by get-config.sh from Dark Flow Web UI"
      echo "# Edit routines in the Web UI Settings tab (Settings > Routine schedule)."
      echo ""
      echo "defaults:"
      echo "  model: sonnet"
      echo "  engine: claude"
      echo "  permission_mode: bypassPermissions"
      echo ""
      echo "routines:"
      echo "$routines_json" | jq -r '.[] | (
        "  " + .name + ":",
        "    cron: \"" + (.cron // "0 * * * *") + "\"",
        "    model: " + (.model // "sonnet"),
        "    engine: " + (.engine // "claude"),
        "    enabled: " + (if .enabled then "true" else "false" end),
        if .permissionMode then "    permission_mode: " + .permissionMode else empty end
      )'
    } > "$ROUTINES_YML"
  fi
fi
