#!/bin/sh
set -eu

SETUP_URL="https://fw.koolcenter.com/binary/kai/kai-skills/setup.sh"
SELECTION="system:istoreos:on-device"

fail() {
	echo "kai-skills-classic: $*" >&2
	exit 2
}

usage() {
	echo "usage: kai-skills-classic {status|install|upgrade}" >&2
	exit 2
}

resolve_data_dir() {
	if [ -n "${KAI_DATA_DIR:-}" ]; then
		printf '%s\n' "$KAI_DATA_DIR"
		return
	fi
	command -v uci >/dev/null 2>&1 || fail "uci is required to resolve the KAI data directory"
	uci -q get 'kai.@kai[0].data_dir' || true
}

validate_data_dir() {
	case "$1" in
		/*) ;;
		*) fail "KAI data directory must be an absolute path" ;;
	esac
	case "$1" in
		/|/tmp|/var|/mnt|/root|/home|*'/../'*|*/..|*'/./'*|*/.|*[![:print:]]*) fail "unsafe KAI data directory" ;;
	esac
}

emit_unavailable() {
	error=$1
	if command -v jq >/dev/null 2>&1; then
		jq -cn --arg target "$target" --arg error "$error" \
			'{ready:false,installed:false,target:$target,error:$error}'
	else
		printf '%s\n' '{"ready":false,"installed":false,"error":"jq is required"}'
	fi
}

status() {
	if ! command -v jq >/dev/null 2>&1; then
		emit_unavailable "jq is required"
		return 3
	fi
	if [ ! -f "$state_file" ]; then
		emit_unavailable "managed iStoreOS skills are not installed"
		return 5
	fi
	if [ -L "$state_dir" ] || [ -L "$state_file" ] || ! jq -e \
		--arg selection "$SELECTION" '
		.schemaVersion == 2 and
		(.packages | type) == "object" and
		(.selections | type) == "object" and
		(.selections[$selection] | type) == "object" and
		.selections[$selection].platform == "istoreos" and
		.selections[$selection].mode == "on-device" and
		.selections[$selection].consumer == "opencode" and
		.selections[$selection].scope == "user" and
		(.selections[$selection].release | type) == "string" and
		(.selections[$selection].members | type) == "array" and
		(.selections[$selection].members | length) > 0
	' "$state_file" >/dev/null 2>&1; then
		emit_unavailable "managed skills ownership state is invalid"
		return 4
	fi

	members="$(jq -r --arg selection "$SELECTION" '.selections[$selection].members[].id' "$state_file")"
	count=0
	for member in $members; do
		case "$member" in
			''|*[!a-z0-9-]*)
				emit_unavailable "managed skills ownership state contains an unsafe member"
				return 4
				;;
		esac
		if [ ! -f "$target/$member/SKILL.md" ] || [ -L "$target/$member" ]; then
			emit_unavailable "managed skill payload is incomplete: $member"
			return 5
		fi
		count=$((count + 1))
	done
	release="$(jq -r --arg selection "$SELECTION" '.selections[$selection].release' "$state_file")"
	jq -cn --arg target "$target" --arg release "$release" --arg selection "$SELECTION" \
		--argjson count "$count" \
		'{ready:true,installed:true,target:$target,selection:$selection,release:$release,skillCount:$count}'
}

require_install_tools() {
	command -v jq >/dev/null 2>&1 || fail "jq is required; install the Classic KAI package prerequisites"
	if ! command -v curl >/dev/null 2>&1 && ! command -v wget >/dev/null 2>&1; then
		fail "curl or wget is required for the first kai-skills bootstrap"
	fi
}

download_setup() {
	destination=$1
	if command -v curl >/dev/null 2>&1; then
		curl -fsSL --connect-timeout 10 --max-time 60 -o "$destination" "$SETUP_URL"
	else
		wget -q -T 60 -O "$destination" "$SETUP_URL"
	fi
	[ -s "$destination" ] || fail "downloaded kai-skills setup is empty"
}

apply_selection() {
	action=$1
	require_install_tools
	if [ "$action" = upgrade ] && [ ! -f "$state_file" ]; then
		fail "managed iStoreOS skills are not installed; run install first"
	fi

	mkdir -p "$data_dir/home" "$data_dir/cache" "$data_dir/config/opencode" "$data_dir/data"
	work="$(mktemp -d "$data_dir/cache/kai-skills-setup.XXXXXX")"
	trap 'rm -rf "$work"' EXIT HUP INT TERM
	setup="$work/setup.sh"
	download_setup "$setup"
	chmod 700 "$setup"

	set -- --system istoreos --mode on-device --consumer opencode --scope user \
		--target-skills "$target" --json
	[ "$action" = install ] || set -- "$@" --upgrade
	HOME="$data_dir/home" \
	XDG_CONFIG_HOME="$data_dir/config" \
	XDG_DATA_HOME="$data_dir/data" \
	XDG_CACHE_HOME="$data_dir/cache" \
	ZSETUP_ROOT="$data_dir/data/zsetup" \
	KAI_SKILLS_WORK_BASE="$data_dir/cache" \
		sh "$setup" "$@" >"$work/installer-result.json"
	if [ -s "$work/installer-result.json" ]; then
		cat "$work/installer-result.json" >&2
	fi

	status >/dev/null || fail "kai-skills completed without a healthy managed selection"
	trap - EXIT HUP INT TERM
	rm -rf "$work"
	status
}

operation=${1:-}
[ "$#" -eq 1 ] || usage
data_dir="$(resolve_data_dir)"
[ -n "$data_dir" ] || fail "KAI data directory is not configured"
data_dir=${data_dir%/}
validate_data_dir "$data_dir"
target="$data_dir/config/opencode/skills"
state_dir="$target/.linkease-skills"
state_file="$state_dir/business-state.json"

case "$operation" in
	status) status ;;
	install) apply_selection install ;;
	upgrade) apply_selection upgrade ;;
	*) usage ;;
esac
