#!/usr/bin/env bash
set -uo pipefail

VERSION="0.1.0"
SKILLS_FILE="${SKILLS_FILE:-$HOME/.config/skills}"
HARNESSES_FILE="${HARNESSES_FILE:-$HOME/.config/harnesses}"
LOCK_FILE="${SKILLS_AUTOUPDATE_LOCK:-${XDG_CACHE_HOME:-$HOME/.cache}/skills-autoupdate.lock}"

export GIT_TERMINAL_PROMPT=0
export GIT_ASKPASS=/bin/true
export GIT_SSH_COMMAND="${GIT_SSH_COMMAND:-ssh -o BatchMode=yes}"

failures=0

usage() {
	cat <<EOF
Usage: skills-autoupdate [-h] [-V]

Keeps the skills listed in $SKILLS_FILE up to date, via git,
in the skills folder of every harness listed in $HARNESSES_FILE.

Environment:
  SKILLS_FILE     list of skills (default ~/.config/skills)
  HARNESSES_FILE  list of harnesses (default ~/.config/harnesses)
EOF
}

log() {
	printf '%s %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$*"
}

warn() {
	log "WARN $*"
}

fail() {
	log "ERROR $*"
	failures=$((failures + 1))
}

expand_path() {
	local p="$1"
	case "$p" in
		\~) p="$HOME" ;;
		\~/*) p="$HOME/${p:2}" ;;
		/*) ;;
		*) p="$HOME/$p" ;;
	esac
	printf '%s\n' "${p%/}"
}

default_root() {
	case "$1" in
		claude) printf '%s\n' "$HOME/.claude" ;;
		codex) printf '%s\n' "$HOME/.codex" ;;
		opencode) printf '%s\n' "${XDG_CONFIG_HOME:-$HOME/.config}/opencode" ;;
		antigravity) printf '%s\n' "$HOME/.gemini/antigravity" ;;
		pi) printf '%s\n' "$HOME/.pi/agent" ;;
		cursor) printf '%s\n' "$HOME/.cursor" ;;
		kimi) printf '%s\n' "$HOME/.kimi" ;;
		zcode) printf '%s\n' "$HOME/.zcode" ;;
		*) return 1 ;;
	esac
}

normalize_name() {
	case "$1" in
		claude | claude-code | claudecode) echo claude ;;
		codex | openai-codex) echo codex ;;
		opencode) echo opencode ;;
		antigravity | agy | gemini-antigravity) echo antigravity ;;
		pi | pi-agent | pi-coding-agent) echo pi ;;
		cursor | cursor-agent) echo cursor ;;
		kimi | kimi-cli) echo kimi ;;
		zcode | z-code | glm) echo zcode ;;
		*) return 1 ;;
	esac
}

detect_harness() {
	local d="$1" base
	[ -f "$d/opencode.json" ] || [ -f "$d/opencode.jsonc" ] && { echo opencode; return 0; }
	[ -f "$d/kimi.json" ] && { echo kimi; return 0; }
	[ -d "$d/cli/plugins" ] && [ -d "$d/workspace" ] && { echo zcode; return 0; }
	[ -f "$d/cli/config.json" ] && [ -d "$d/v2" ] && { echo zcode; return 0; }
	[ -f "$d/.credentials.json" ] || [ -f "$d/CLAUDE.md" ] || [ -f "$d/.claude.json" ] && { echo claude; return 0; }
	[ -f "$d/config.toml" ] && { [ -f "$d/AGENTS.md" ] || [ -f "$d/auth.json" ] || [ -f "$d/installation_id" ] || [ -d "$d/sessions" ]; } && { echo codex; return 0; }
	[ -f "$d/mcp_config.json" ] || [ -d "$d/brain" ] && { echo antigravity; return 0; }
	[ -f "$d/models.json" ] && [ -f "$d/settings.json" ] && { echo pi; return 0; }
	[ -f "$d/argv.json" ] || [ -f "$d/cli-config.json" ] || [ -f "$d/ide_state.json" ] && { echo cursor; return 0; }
	[ -d "$d/projects" ] && [ -f "$d/settings.json" ] && { echo claude; return 0; }
	base="$(basename "$d" | tr '[:upper:]' '[:lower:]')"
	case "$d" in
		*/.pi/agent) echo pi; return 0 ;;
		*/antigravity*) echo antigravity; return 0 ;;
	esac
	local h
	for h in opencode antigravity claude codex cursor kimi zcode; do
		case "$base" in
			*"$h"*) echo "$h"; return 0 ;;
		esac
	done
	return 1
}

skills_dir() {
	printf '%s/skills\n' "$1"
}

strip_comment() {
	local line="${1%%#*}"
	line="${line#"${line%%[![:space:]]*}"}"
	line="${line%"${line##*[![:space:]]}"}"
	printf '%s' "$line"
}

version_gt() {
	[ "$1" != "$2" ] && [ "$(printf '%s\n%s\n' "$1" "$2" | sort -V | tail -n 1)" = "$1" ]
}

best_tag() {
	local dir="$1" op="$2" ref="${3#v}" t v best="" best_v=""
	while IFS= read -r t; do
		v="${t#v}"
		case "$op" in
			">") version_gt "$v" "$ref" || continue ;;
			">=") [ "$v" = "$ref" ] || version_gt "$v" "$ref" || continue ;;
		esac
		if [ -z "$best" ] || version_gt "$v" "$best_v"; then
			best="$t"
			best_v="$v"
		fi
	done < <(git -C "$dir" tag -l | grep -E '^v?[0-9]')
	[ -n "$best" ] && printf '%s\n' "$best"
}

describe() {
	git -C "$1" describe --tags --always --exact-match HEAD 2>/dev/null || git -C "$1" rev-parse --short HEAD
}

sync_skill() {
	local harness="$1" dir="$2" url="$3" op="$4" ref="$5"
	local tag
	tag="[$harness] ${dir##*/}"
	local before after target branch origin

	if [ ! -e "$dir" ]; then
		if ! git clone -q "$url" "$dir" 2>&1; then
			fail "$tag: clone of $url failed"
			return
		fi
		log "$tag: cloned $url"
		before=""
	else
		if [ ! -d "$dir/.git" ]; then
			warn "$tag: $dir exists but is not a git checkout, skipped"
			return
		fi
		origin="$(git -C "$dir" remote get-url origin 2>/dev/null || true)"
		if [ "${origin%.git}" != "${url%.git}" ]; then
			warn "$tag: origin is '$origin', expected '$url', skipped"
			return
		fi
		if [ -n "$(git -C "$dir" status --porcelain 2>/dev/null)" ]; then
			warn "$tag: local changes present, skipped"
			return
		fi
		if ! git -C "$dir" fetch -q --prune --tags --force origin 2>&1; then
			fail "$tag: fetch failed"
			return
		fi
		before="$(git -C "$dir" rev-parse HEAD)"
	fi

	case "$op" in
		"")
			git -C "$dir" remote set-head origin -a >/dev/null 2>&1 || true
			branch="$(git -C "$dir" symbolic-ref -q --short refs/remotes/origin/HEAD)"
			branch="${branch#origin/}"
			if [ -z "$branch" ]; then
				fail "$tag: cannot find the default branch"
				return
			fi
			if ! git -C "$dir" checkout -q "$branch" 2>&1 || ! git -C "$dir" merge -q --ff-only "origin/$branch" 2>&1; then
				fail "$tag: cannot fast-forward $branch to origin/$branch"
				return
			fi
			;;
		"=")
			target="$(git -C "$dir" rev-parse -q --verify "refs/tags/$ref^{commit}" 2>/dev/null ||
				git -C "$dir" rev-parse -q --verify "refs/tags/v${ref#v}^{commit}" 2>/dev/null ||
				git -C "$dir" rev-parse -q --verify "$ref^{commit}" 2>/dev/null)"
			if [ -z "$target" ]; then
				fail "$tag: ref '$ref' not found"
				return
			fi
			if [ "$target" != "$(git -C "$dir" rev-parse HEAD)" ] && ! git -C "$dir" checkout -q --detach "$target" 2>&1; then
				fail "$tag: checkout of $ref failed"
				return
			fi
			;;
		">" | ">=")
			target="$(best_tag "$dir" "$op" "$ref")"
			if [ -z "$target" ]; then
				warn "$tag: no tag $op $ref, left at $(describe "$dir")"
				return
			fi
			if [ "$(git -C "$dir" rev-parse "refs/tags/$target^{commit}")" != "$(git -C "$dir" rev-parse HEAD)" ] &&
				! git -C "$dir" checkout -q --detach "refs/tags/$target" 2>&1; then
				fail "$tag: checkout of $target failed"
				return
			fi
			;;
	esac

	after="$(git -C "$dir" rev-parse HEAD)"
	if [ -z "$before" ]; then
		log "$tag: at $(describe "$dir")"
	elif [ "$before" != "$after" ]; then
		log "$tag: updated ${before:0:10} -> $(describe "$dir")"
	else
		log "$tag: up to date at $(describe "$dir")"
	fi
}

main() {
	case "${1:-}" in
		-h | --help) usage; exit 0 ;;
		-V | --version) echo "skills-autoupdate $VERSION"; exit 0 ;;
		"") ;;
		*) usage >&2; exit 2 ;;
	esac

	command -v git >/dev/null || { log "ERROR git not found"; exit 1; }
	[ -r "$SKILLS_FILE" ] || { log "ERROR $SKILLS_FILE not found"; exit 1; }
	[ -r "$HARNESSES_FILE" ] || { log "ERROR $HARNESSES_FILE not found"; exit 1; }

	if command -v flock >/dev/null; then
		mkdir -p "$(dirname "$LOCK_FILE")"
		exec 9>"$LOCK_FILE"
		flock -n 9 || { log "another run is in progress, exiting"; exit 0; }
	fi

	local -a h_names=() h_roots=() s_urls=() s_ops=() s_refs=() s_names=()
	local raw line name root real seen="" i j

	while IFS= read -r raw || [ -n "$raw" ]; do
		line="$(strip_comment "$raw")"
		[ -z "$line" ] && continue
		if name="$(normalize_name "$(printf '%s' "$line" | tr '[:upper:]' '[:lower:]')")"; then
			root="$(default_root "$name")"
		else
			root="$(expand_path "$line")"
			if [ ! -d "$root" ]; then
				warn "harness path $root not found, skipped"
				continue
			fi
			if ! name="$(detect_harness "$root")"; then
				warn "cannot recognize the harness in $root, skipped"
				continue
			fi
		fi
		if [ ! -d "$root" ]; then
			log "[$name] $root not found, harness not installed, skipped"
			continue
		fi
		real="$(cd "$root" && pwd -P)"
		case "$seen" in
			*"|$real|"*) continue ;;
		esac
		seen="$seen|$real|"
		h_names+=("$name")
		h_roots+=("$root")
	done <"$HARNESSES_FILE"

	while IFS= read -r raw || [ -n "$raw" ]; do
		line="$(strip_comment "$raw")"
		[ -z "$line" ] && continue
		if [[ ! "$line" =~ ^([^=\>[:space:]]+)(\>=|\>|=)?([^[:space:]]*)$ ]]; then
			warn "invalid skill line '$line', skipped"
			continue
		fi
		if [ -n "${BASH_REMATCH[2]}" ] && [ -z "${BASH_REMATCH[3]}" ]; then
			warn "missing version in '$line', skipped"
			continue
		fi
		s_urls+=("${BASH_REMATCH[1]}")
		s_ops+=("${BASH_REMATCH[2]}")
		s_refs+=("${BASH_REMATCH[3]}")
		name="${BASH_REMATCH[1]%/}"
		name="${name##*/}"
		name="${name##*:}"
		s_names+=("${name%.git}")
	done <"$SKILLS_FILE"

	[ "${#h_names[@]}" -eq 0 ] && { log "no harness found, nothing to do"; exit 0; }
	[ "${#s_urls[@]}" -eq 0 ] && { log "no skill listed, nothing to do"; exit 0; }

	for i in "${!h_names[@]}"; do
		root="$(skills_dir "${h_roots[$i]}")"
		if ! mkdir -p "$root"; then
			fail "[${h_names[$i]}] cannot create $root"
			continue
		fi
		for j in "${!s_urls[@]}"; do
			sync_skill "${h_names[$i]}" "$root/${s_names[$j]}" "${s_urls[$j]}" "${s_ops[$j]}" "${s_refs[$j]}"
		done
	done

	[ "$failures" -eq 0 ] || { log "finished with $failures error(s)"; exit 1; }
	log "finished"
}

main "$@"
