#!/usr/bin/env bash
# ReasonKit Installer v2.0.0 - Interactive by Default
# https://get.reasonkit.sh | https://reasonkit.sh/install
#
# Usage:
#   curl -fsSL https://get.reasonkit.sh | bash           # Interactive (default)
#   curl -fsSL https://get.reasonkit.sh | bash -s -- -y  # Non-interactive (CI/CD)
#   curl -fsSL https://get.reasonkit.sh | bash -s -- --full -y
#
# Installation modes:
#   default         Core reasoning engine (ThinkTools, protocols)
#   --with-memory   Include RAG, vector search, knowledge base features
#   --full          All components: Core + Web + Memory + Skills + Commands
#
# Environment variables:
#   RK_VERSION         Version to install (default: latest)
#   RK_INSTALL_DIR     Installation directory (default: ~/.reasonkit)
#   RK_BIN_DIR         Binary directory (default: ~/.local/bin)
#   RK_NO_MODIFY_PATH  Set to 1 to skip PATH modification

# ============================================================
# Strict Mode & Trap Setup
# ============================================================
set -euo pipefail

CLEANUP_DIRS=()
cleanup() {
	local exit_code=$?
	if [ ${#CLEANUP_DIRS[@]} -gt 0 ]; then
		for dir in "${CLEANUP_DIRS[@]}"; do
			[ -d "$dir" ] && rm -rf "$dir" 2>/dev/null || true
		done
	fi
	if [ $exit_code -ne 0 ]; then
		echo ""
		error_msg "Installation failed with exit code $exit_code"
		if [ -n "${ROLLBACK_BINARY:-}" ] && [ -f "$ROLLBACK_BINARY" ]; then
			warn_msg "Rolling back: removing $ROLLBACK_BINARY"
			rm -f "$ROLLBACK_BINARY" 2>/dev/null || true
		fi
		echo ""
		info_msg "For help, visit: https://reasonkit.sh/docs/install"
		info_msg "Or file an issue: https://github.com/reasonkit/reasonkit-core/issues"
	fi
	exit $exit_code
}
trap cleanup EXIT

# ============================================================
# Configuration
# ============================================================
VERSION="${RK_VERSION:-latest}"
INSTALL_DIR="${RK_INSTALL_DIR:-$HOME/.reasonkit}"
BIN_DIR="${RK_BIN_DIR:-$HOME/.local/bin}"
REPO_URL="https://github.com/reasonkit/reasonkit-core"
RELEASES_URL="https://github.com/reasonkit/reasonkit-core/releases"
INTEGRATIONS_URL="https://raw.githubusercontent.com/reasonkit/reasonkit-core/main/integrations"
MIN_RUST_VERSION="1.70.0"
INSTALLER_VERSION="2.0.0"

ROLLBACK_BINARY=""

# ============================================================
# Terminal & Color Detection
# ============================================================
setup_colors() {
	if [ -t 1 ] && command -v tput >/dev/null 2>&1 && [ "$(tput colors 2>/dev/null || echo 0)" -ge 8 ]; then
		RED='\033[0;31m'
		GREEN='\033[0;32m'
		YELLOW='\033[0;33m'
		BLUE='\033[0;34m'
		CYAN='\033[0;36m'
		BOLD='\033[1m'
		DIM='\033[2m'
		NC='\033[0m'
	else
		RED='' GREEN='' YELLOW='' BLUE='' CYAN='' BOLD='' DIM='' NC=''
	fi
}

# ============================================================
# Output Utilities
# ============================================================
info_msg() { echo -e "${CYAN}[INFO]${NC} $1"; }
success_msg() { echo -e "${GREEN}[OK]${NC} $1"; }
warn_msg() { echo -e "${YELLOW}[WARN]${NC} $1"; }
error_msg() { echo -e "${RED}[ERROR]${NC} $1" >&2; }
debug_msg() { [ "${DEBUG:-0}" = "1" ] && echo -e "${DIM}[DEBUG] $1${NC}" || true; }

progress_start() {
	local msg="$1"
	if [ -t 1 ]; then
		echo -ne "${CYAN}[....]${NC} $msg"
		PROGRESS_MSG="$msg"
	else
		echo -e "${CYAN}[....]${NC} $msg"
	fi
}

progress_done() { [ -t 1 ] && echo -ne "\r${GREEN}[OK]${NC}   ${PROGRESS_MSG:-}\n" || true; }
progress_fail() { [ -t 1 ] && echo -ne "\r${RED}[FAIL]${NC} ${PROGRESS_MSG:-}\n" || true; }

# Simple Yes/No prompt - returns 0 for yes, 1 for no
# Reads from /dev/tty to work when script is piped (curl ... | bash)
ask_yes_no() {
	local prompt="$1"
	local default="${2:-y}" # default to yes

	# Non-interactive mode: use default
	if $NON_INTERACTIVE; then
		[ "$default" = "y" ] && return 0 || return 1
	fi

	# Check if we can read from terminal (required for interactive prompts)
	# When piped via curl, stdin is the pipe, so we must use /dev/tty
	if [ ! -t 0 ] && [ ! -e /dev/tty ]; then
		# No terminal available, use default silently
		[ "$default" = "y" ] && return 0 || return 1
	fi

	local yn_hint
	[ "$default" = "y" ] && yn_hint="[Y/n]" || yn_hint="[y/N]"

	local response=""
	echo -ne "${BOLD}$prompt${NC} $yn_hint: "

	# Read from /dev/tty (terminal) instead of stdin
	# This allows interactive prompts even when script is piped
	if [ -t 0 ]; then
		# stdin is a terminal, read normally
		read -r response
	elif [ -e /dev/tty ]; then
		# stdin is a pipe (curl | bash), read from terminal device
		# Wrap in command group to suppress redirect errors (containers, CI)
		{ read -r response </dev/tty; } 2>/dev/null || response=""
	fi

	# Use tr for lowercase (bash 3.2 compatible - macOS default)
	local response_lower
	response_lower="$(echo "$response" | tr '[:upper:]' '[:lower:]')"
	case "$response_lower" in
	y | yes) return 0 ;;
	n | no) return 1 ;;
	"") [ "$default" = "y" ] && return 0 || return 1 ;;
	*) [ "$default" = "y" ] && return 0 || return 1 ;;
	esac
}

# ============================================================
# Flags (Interactive by default!)
# ============================================================
NON_INTERACTIVE=false
FULL_INSTALL=false
WITH_MCP=false
WITH_SKILLS=false
WITH_COMMANDS=false
WITH_MEMORY=false
WITH_WEB=false
QUIET=false
FORCE=false
SKIP_VERIFY=false

# Detected tools
DETECTED_TOOLS=()

# ============================================================
# Banner
# ============================================================
banner() {
	echo -e "${CYAN}"
	cat <<'EOF'
    ____                            __ __ _ __
   / __ \___  ____ ________  ____  / //_/(_) /_
  / /_/ / _ \/ __ `/ ___/ / / / / / ,<  / / __/
 / _, _/  __/ /_/ (__  ) /_/ / / / /| |/ / /_
/_/ |_|\___/\__,_/____/\____/ /_/_/ |_/_/\__/

EOF
	echo -e "${NC}"
	echo -e "${DIM}    Turn Prompts into Protocols${NC}"
	echo -e "${DIM}    https://reasonkit.sh${NC}"
	echo ""
}

# ============================================================
# Platform Detection
# ============================================================
detect_platform() {
	local os arch kernel
	kernel="$(uname -s)"
	case "$kernel" in
	Linux*)
		if grep -qiE "(microsoft|wsl)" /proc/version 2>/dev/null; then
			os="linux-wsl"
			info_msg "Detected: Windows Subsystem for Linux (WSL)"
		else
			os="linux"
		fi
		;;
	Darwin*) os="darwin" ;;
	MINGW* | MSYS* | CYGWIN*)
		os="windows"
		warn_msg "Native Windows detected. Consider using WSL for best experience."
		;;
	FreeBSD*)
		os="freebsd"
		warn_msg "FreeBSD support is experimental"
		;;
	*)
		error_msg "Unsupported operating system: $kernel"
		exit 1
		;;
	esac

	local machine
	machine="$(uname -m)"
	case "$machine" in
	x86_64 | amd64) arch="x86_64" ;;
	arm64 | aarch64) arch="aarch64" ;;
	armv7l | armhf)
		arch="armv7"
		warn_msg "ARM 32-bit support is limited"
		;;
	i386 | i686)
		error_msg "32-bit x86 is not supported"
		exit 1
		;;
	*)
		error_msg "Unsupported architecture: $machine"
		exit 1
		;;
	esac

	echo "${os}-${arch}"
}

# ============================================================
# Dependency Checks
# ============================================================
check_rust() {
	if ! command -v cargo >/dev/null 2>&1; then
		warn_msg "Rust/Cargo not found"
		echo ""
		info_msg "ReasonKit is built with Rust for maximum performance."
		info_msg "Install Rust using rustup:"
		echo ""
		echo "    curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh"
		echo ""
		info_msg "Then re-run this installer."
		exit 1
	fi

	local rust_version
	rust_version=$(rustc --version 2>/dev/null | cut -d' ' -f2 || echo "0.0.0")
	if ! version_gte "$rust_version" "$MIN_RUST_VERSION"; then
		warn_msg "Rust version $rust_version is older than recommended ($MIN_RUST_VERSION)"
		info_msg "Update with: rustup update stable"
	fi
}

check_dependencies() {
	local missing=()
	if ! command -v git >/dev/null 2>&1; then missing+=("git"); fi
	if ! command -v curl >/dev/null 2>&1 && ! command -v wget >/dev/null 2>&1; then
		missing+=("curl or wget")
	fi

	if [ ${#missing[@]} -gt 0 ]; then
		error_msg "Missing required dependencies: ${missing[*]}"
		echo ""
		info_msg "Please install the missing dependencies and try again."
		exit 1
	fi

	check_rust
	success_msg "All dependencies satisfied"
}

version_gte() {
	[ "$(printf '%s\n' "$2" "$1" | sort -V | head -n1)" = "$2" ]
}

# ============================================================
# Existing Installation Detection
# ============================================================
check_existing_installation() {
	local existing_binary="" existing_version=""

	for bin_path in "$BIN_DIR/rk" "$BIN_DIR/rk-core" "$HOME/.cargo/bin/rk"; do
		if [ -x "$bin_path" ]; then
			existing_binary="$bin_path"
			existing_version=$("$bin_path" --version 2>/dev/null | head -n1 || echo "unknown")
			break
		fi
	done

	if [ -z "$existing_binary" ] && command -v rk >/dev/null 2>&1; then
		existing_binary=$(command -v rk)
		existing_version=$(rk --version 2>/dev/null | head -n1 || echo "unknown")
	fi

	if [ -n "$existing_binary" ]; then
		echo ""
		warn_msg "Existing ReasonKit installation detected!"
		info_msg "Location: $existing_binary"
		info_msg "Version: $existing_version"
		echo ""

		if $FORCE || $NON_INTERACTIVE; then
			info_msg "Proceeding with upgrade..."
		elif ask_yes_no "Upgrade existing installation?"; then
			info_msg "Proceeding with upgrade..."
		else
			info_msg "Keeping existing installation"
			verify_installation "$existing_binary"
			exit 0
		fi
	fi
}

# ============================================================
# Tool Detection - Extended for all AI tools
# ============================================================
detect_tools() {
	if ! $QUIET; then
		info_msg "Detecting installed AI tools..."
	fi

	# Claude Code
	if command -v claude >/dev/null 2>&1; then
		DETECTED_TOOLS+=("claude")
		! $QUIET && success_msg "Found: Claude Code"
	fi

	# Cursor
	if command -v cursor >/dev/null 2>&1 || [ -d "$HOME/.cursor" ] || [ -d "/Applications/Cursor.app" ]; then
		DETECTED_TOOLS+=("cursor")
		! $QUIET && success_msg "Found: Cursor"
	fi

	# VS Code
	if command -v code >/dev/null 2>&1 || [ -d "/Applications/Visual Studio Code.app" ]; then
		DETECTED_TOOLS+=("vscode")
		! $QUIET && success_msg "Found: VS Code"
	fi

	# Windsurf
	if command -v windsurf >/dev/null 2>&1 || [ -d "$HOME/.windsurf" ]; then
		DETECTED_TOOLS+=("windsurf")
		! $QUIET && success_msg "Found: Windsurf"
	fi

	# Gemini CLI
	if command -v gemini >/dev/null 2>&1; then
		DETECTED_TOOLS+=("gemini")
		! $QUIET && success_msg "Found: Gemini CLI"
	fi

	# Codex CLI
	if command -v codex >/dev/null 2>&1; then
		DETECTED_TOOLS+=("codex")
		! $QUIET && success_msg "Found: Codex CLI"
	fi

	# Grok CLI
	if command -v grok >/dev/null 2>&1; then
		DETECTED_TOOLS+=("grok")
		! $QUIET && success_msg "Found: Grok CLI"
	fi

	# OpenCode
	if command -v opencode >/dev/null 2>&1 || [ -d "$HOME/.opencode" ]; then
		DETECTED_TOOLS+=("opencode")
		! $QUIET && success_msg "Found: OpenCode"
	fi

	# GitHub Copilot CLI
	if command -v gh >/dev/null 2>&1 && gh extension list 2>/dev/null | grep -q copilot; then
		DETECTED_TOOLS+=("copilot")
		! $QUIET && success_msg "Found: GitHub Copilot CLI"
	fi

	# Aider
	if command -v aider >/dev/null 2>&1; then
		DETECTED_TOOLS+=("aider")
		! $QUIET && success_msg "Found: Aider"
	fi

	if [ ${#DETECTED_TOOLS[@]} -eq 0 ]; then
		! $QUIET && echo -e "${DIM}No AI tools detected${NC}"
	fi
	! $QUIET && echo ""
}

# ============================================================
# Installation Functions
# ============================================================
install_core() {
	info_msg "Installing reasonkit-core..."

	local features_flag=""
	$WITH_MEMORY && features_flag="--features memory"

	mkdir -p "$BIN_DIR" "$INSTALL_DIR"
	ROLLBACK_BINARY="$BIN_DIR/rk"

	progress_start "Installing with Cargo..."
	if cargo install --git "$REPO_URL" --locked $features_flag 2>&1; then
		progress_done
	else
		progress_fail
		warn_msg "Cargo install failed, trying local build..."

		local tmp_dir
		tmp_dir=$(mktemp -d)
		CLEANUP_DIRS+=("$tmp_dir")

		progress_start "Cloning repository..."
		if ! git clone --depth 1 "$REPO_URL" "$tmp_dir/rk" 2>&1; then
			progress_fail
			error_msg "Failed to clone repository"
			exit 1
		fi
		progress_done

		progress_start "Building from source..."
		cd "$tmp_dir/rk"
		
		# Use local cargo target directory if the default is not writable
		local cargo_target_arg=""
		if [ -w "$HOME/.cargo/target" ] 2>/dev/null || mkdir -p "$HOME/.cargo/target" 2>/dev/null; then
			cargo_target_arg="--target-dir $HOME/.cargo/target"
		fi
		
		local build_cmd="cargo build --release $cargo_target_arg"
		$WITH_MEMORY && build_cmd="cargo build --release --features memory $cargo_target_arg"

		# Run build, capturing output
		if ! (cd "$tmp_dir/rk" && eval "$build_cmd") 2>&1; then
			progress_fail
			error_msg "Build failed - see errors above"
			exit 1
		fi
		progress_done

		progress_start "Installing binary..."
		if [ -f "target/release/rk" ]; then
			cp "target/release/rk" "$BIN_DIR/rk"
		else
			progress_fail
			error_msg "Binary not found"
			exit 1
		fi
		chmod +x "$BIN_DIR/rk"
		progress_done

		rm -rf "$tmp_dir"
		CLEANUP_DIRS=()
	fi

	# Create backwards-compat symlink (rk-core -> rk)
	[ -f "$BIN_DIR/rk" ] && [ ! -f "$BIN_DIR/rk-core" ] && ln -sf "$BIN_DIR/rk" "$BIN_DIR/rk-core" 2>/dev/null || true

	ROLLBACK_BINARY=""
	success_msg "reasonkit-core installed!"
}

install_mcp() {
	info_msg "Configuring MCP Server..."
	mkdir -p "$INSTALL_DIR"

	cat >"$INSTALL_DIR/mcp-config.json" <<'MCPEOF'
{
  "mcpServers": {
    "reasonkit": {
      "command": "rk",
      "args": ["mcp", "serve"],
      "env": {},
      "description": "ReasonKit ThinkTools - Structured reasoning protocols"
    }
  }
}
MCPEOF
	success_msg "MCP Server configured at $INSTALL_DIR/mcp-config.json"
}

# ============================================================
# Claude Code Integration - Full Commands & Skills
# ============================================================
install_claude_commands() {
	info_msg "Installing Claude Code commands (/rk-* slash commands)..."
	local commands_dir="$HOME/.claude/commands"
	mkdir -p "$commands_dir"

	# Download commands from integrations (or use embedded)
	local commands=(
		"rk-help" "rk-think" "rk-logic" "rk-deep" "rk-quick" "rk-scientific"
		"rk-paranoid" "rk-decide" "rk-verify" "rk-research" "rk-roots"
		"rk-reflect" "rk-creative" "rk-debug" "rk-ethics" "rk-forecast"
		"rk-network" "rk-risk" "rk-science"
	)

	local count=0
	for cmd in "${commands[@]}"; do
		# Try to download, or create minimal placeholder
		if curl -fsSL "$INTEGRATIONS_URL/claude/commands/${cmd}.md" -o "$commands_dir/${cmd}.md" 2>/dev/null; then
			((count++))
		fi
	done

	if [ $count -gt 0 ]; then
		success_msg "Claude Code commands installed ($count commands)"
		echo -e "${DIM}  Use /rk-help to see all available commands${NC}"
	else
		# Create embedded minimal commands
		create_embedded_claude_commands "$commands_dir"
		success_msg "Claude Code commands installed (embedded)"
	fi
}

create_embedded_claude_commands() {
	local dir="$1"

	# rk-help
	cat >"$dir/rk-help.md" <<'EOF'
# ReasonKit Command Reference

## Core Commands
| Command | Purpose |
|---------|---------|
| `/rk-think` | Deep comprehensive analysis (GigaThink) |
| `/rk-logic` | Precision deductive reasoning (LaserLogic) |
| `/rk-verify` | Fact verification (ProofGuard) |
| `/rk-roots` | Root cause analysis (MaxRoots) |
| `/rk-reflect` | Self-assessment & bias detection |

## Profiles
| Command | Confidence | Use For |
|---------|------------|---------|
| `/rk-quick` | 70% | Fast drafts |
| `/rk-deep` | 85% | Important decisions |
| `/rk-scientific` | 85% | Research |
| `/rk-paranoid` | 95% | Critical verification |

## Workflows
| `/rk-decide` | Full-stack decision making |

Type any command followed by your question.
EOF

	# rk-think
	cat >"$dir/rk-think.md" <<'EOF'
# ReasonKit GigaThink - Deep Comprehensive Analysis

Apply **GigaThink** for expansive, multi-perspective analysis.

## Process
1. Generate 10+ diverse perspectives
2. Consider edge cases and implications
3. Synthesize insights
4. Provide confidence assessment

## Output Format
```
GIGATHINK ANALYSIS
==================
PERSPECTIVES: [10+ viewpoints]
SYNTHESIS: [Key insights]
CONFIDENCE: [X]%
```

## Your Task
Analyze: $ARGUMENTS
EOF

	# rk-logic
	cat >"$dir/rk-logic.md" <<'EOF'
# ReasonKit LaserLogic - Precision Deductive Reasoning

Apply **LaserLogic** for formal logical analysis.

## Process
1. Extract premises and claims
2. Build logical argument structure
3. Check for fallacies
4. Validate conclusions

## Output Format
```
LASERLOGIC ANALYSIS
===================
PREMISES: [List]
REASONING: [Steps]
FALLACIES: [Detected issues]
CONCLUSION: [Valid/Invalid]
CONFIDENCE: [X]%
```

## Your Task
Analyze: $ARGUMENTS
EOF

	# rk-quick
	cat >"$dir/rk-quick.md" <<'EOF'
# ReasonKit Quick Profile - Fast Analysis Mode

Apply **Quick** profile for rapid insights (70% confidence).

## Configuration
- GigaThink: Mode=fast
- LaserLogic: Strictness=lenient

## Output Format
```
QUICK ANALYSIS
==============
KEY POINTS: [3-5 insights]
RECOMMENDATION: [Action]
CONFIDENCE: 70%
```

## Your Task
Quick analysis of: $ARGUMENTS
EOF

	# rk-deep
	cat >"$dir/rk-deep.md" <<'EOF'
# ReasonKit Deep Profile - Thorough Analysis Mode

Apply **Deep** profile for comprehensive analysis (85% confidence).

## Configuration
- GigaThink: Mode=deep, Depth=8
- LaserLogic: Strictness=classical
- ProofGuard: Strictness=rigorous

## Output Format
```
DEEP ANALYSIS
=============
PROBLEM FRAMING: [Precise statement]
COMPREHENSIVE ANALYSIS: [Multi-perspective]
EVIDENCE BASE: [Sources]
RISK ASSESSMENT: [Key risks]
CONCLUSION: [Well-supported]
CONFIDENCE: 85%
```

## Your Task
Deep analysis of: $ARGUMENTS
EOF

	# rk-paranoid
	cat >"$dir/rk-paranoid.md" <<'EOF'
# ReasonKit Paranoid Profile - Maximum Verification Mode

Apply **Paranoid** profile for critical decisions (95% confidence).

## Configuration
- GigaThink: Mode=exhaustive
- LaserLogic: Strictness=strict
- ProofGuard: Strictness=paranoid
- BrutalHonesty: Enabled

## Process
1. Triple-verify all claims
2. Actively seek counter-evidence
3. Attack own conclusions
4. Document uncertainty

## Output Format
```
PARANOID ANALYSIS
=================
VERIFIED CLAIMS: [With sources]
COUNTER-EVIDENCE: [What argues against]
ATTACK ON CONCLUSION: [Self-critique]
FINAL ASSESSMENT: [After stress-testing]
CONFIDENCE: 95%
```

## Your Task
Paranoid analysis of: $ARGUMENTS
EOF

	# rk-verify
	cat >"$dir/rk-verify.md" <<'EOF'
# ReasonKit ProofGuard - Verification & Fact-Checking

Apply **ProofGuard** for rigorous claim verification.

## Process
1. Identify claims to verify
2. Find 3+ independent sources
3. Assess source quality
4. Triangulate truth

## Output Format
```
PROOFGUARD VERIFICATION
=======================
CLAIM: [Statement]
SOURCES:
  1. [Source] - [Assessment]
  2. [Source] - [Assessment]
  3. [Source] - [Assessment]
VERDICT: [Verified/Unverified/Disputed]
CONFIDENCE: [X]%
```

## Your Task
Verify: $ARGUMENTS
EOF

	# rk-decide
	cat >"$dir/rk-decide.md" <<'EOF'
# ReasonKit Decision Protocol - Full Stack Decision Making

Apply the complete ReasonKit Cognitive Stack for high-stakes decisions.

## Process
1. Frame decision precisely
2. Gather and verify evidence
3. Apply logical analysis
4. Assess risks
5. Consider ethics
6. Check for biases
7. Stress test conclusion
8. Deliver recommendation

## Output Format
```
REASONKIT DECISION ANALYSIS
===========================
DECISION: [Precise question]
OPTIONS: [A, B, C]
EVIDENCE: [Key facts]
LOGICAL ANALYSIS: [Pros/cons]
RISK ASSESSMENT: [By option]
RECOMMENDATION: [Clear choice]
CONFIDENCE: [X]%
NEXT STEPS: [Actions]
```

## Your Task
Decision analysis: $ARGUMENTS
EOF

	# rk-scientific
	cat >"$dir/rk-scientific.md" <<'EOF'
# ReasonKit Scientific Profile - Academic Rigor Mode

Apply **Scientific** profile for research-grade analysis.

## Process
1. Formulate testable hypothesis
2. Systematic evidence review
3. Rigorous logical analysis
4. Acknowledge limitations

## Output Format
```
SCIENTIFIC ANALYSIS
===================
RESEARCH QUESTION: [Precise]
HYPOTHESIS: [H1, H0]
METHODOLOGY: [Approach]
EVIDENCE SYNTHESIS: [Findings]
LIMITATIONS: [Acknowledged]
CONCLUSION: [Evidence-based]
CONFIDENCE: 85%
```

## Your Task
Scientific analysis of: $ARGUMENTS
EOF
}

install_claude_skills() {
	info_msg "Installing Claude Code skills..."
	local skills_dir="$HOME/.claude/skills/reasonkit"
	mkdir -p "$skills_dir"

	# Create directory structure
	mkdir -p "$skills_dir"/{core,thinktools/{gigathink,laserlogic,bedrock,proofguard,brutalhonesty},profiles/powercombo,advanced/{tot,debate},web,mem}

	# Core skill
	cat >"$skills_dir/core/SKILL.md" <<'EOF'
---
name: rk
description: >-
  Master ReasonKit skill - structured reasoning with 5 ThinkTools, 7 profiles,
  and 57% variance reduction. Turn prompts into protocols.
---

# ReasonKit - Structured Reasoning Framework

**"Designed, Not Dreamed. Turn Prompts into Protocols."**

## Profile Selection

| Profile | ThinkTools | Confidence |
|---------|-----------|------------|
| `--quick` | GT → LL | 70% |
| `--balanced` | GT → LL → BR → PG | 80% |
| `--deep` | All 5 + meta | 85% |
| `--paranoid` | All 5 + validation | 95% |

## CLI Usage

```bash
rk think --profile balanced "Should we adopt microservices?"
rk think --profile paranoid "Validate security implementation"
```

## The 5 ThinkTools

1. **GigaThink** - Divergent exploration (10+ perspectives)
2. **LaserLogic** - Logic validation, fallacy detection
3. **BedRock** - First principles decomposition
4. **ProofGuard** - Source triangulation (3+ sources)
5. **BrutalHonesty** - Adversarial self-critique

---

**https://reasonkit.sh**
EOF

	# README
	cat >"$skills_dir/README.md" <<'EOF'
# ReasonKit Skills

**Turn Prompts into Protocols** | https://reasonkit.sh

## Quick Start

```
/rk                    - Master skill
/rk:gigathink          - Divergent exploration
/rk:laserlogic         - Logic validation
/rk:bedrock            - First principles
/rk:proofguard         - Source triangulation
/rk:brutalhonesty      - Adversarial critique
/rk:powercombo         - Full chain (57% variance reduction)
```

## Profiles

| Profile | Modules | Confidence |
|---------|---------|------------|
| `--quick` | 2 | 70% |
| `--balanced` | 4 | 80% |
| `--deep` | 5 | 85% |
| `--paranoid` | 5 + validation | 95% |

---

**ReasonKit** | Apache 2.0 | https://reasonkit.sh
EOF

	success_msg "Claude Code skills installed in $skills_dir"
}

# ============================================================
# Other Tool Integrations
# ============================================================
install_codex_skills() {
	info_msg "Installing Codex CLI skills..."
	local skills_dir="$HOME/.codex/skills/reasonkit"
	mkdir -p "$skills_dir"

	cat >"$skills_dir/SKILL.md" <<'EOF'
---
name: rk
description: ReasonKit structured reasoning protocols for Codex CLI
---

# ReasonKit for Codex CLI

## Quick Start
```bash
codex "Apply ReasonKit --paranoid to: your question"
codex "your question" | rk think --balanced
```

## Profiles
- `--quick` (70%) | `--balanced` (80%) | `--deep` (85%) | `--paranoid` (95%)

---
https://reasonkit.sh
EOF

	success_msg "Codex CLI skills installed"
}

install_gemini_integration() {
	info_msg "Installing Gemini CLI integration..."
	local gemini_dir="$HOME/.gemini"
	mkdir -p "$gemini_dir"

	cat >"$gemini_dir/reasonkit.md" <<'EOF'
# ReasonKit Integration for Gemini CLI

## Quick Start
```bash
gemini -p "Apply ReasonKit --paranoid to: your question"
gemini -p "your question" | rk think --balanced
```

## Profiles
- `--quick` (70%) | `--balanced` (80%) | `--deep` (85%) | `--paranoid` (95%)

---
https://reasonkit.sh
EOF

	success_msg "Gemini CLI integration installed"
}

install_grok_integration() {
	info_msg "Installing Grok CLI integration..."
	local grok_dir="$HOME/.grok"
	mkdir -p "$grok_dir"

	cat >"$grok_dir/reasonkit.md" <<'EOF'
# ReasonKit Integration for Grok CLI

## Quick Start
```bash
grok "Apply ReasonKit --paranoid to: your question"
grok "your question" | rk think --balanced
```

## Profiles
- `--quick` (70%) | `--balanced` (80%) | `--deep` (85%) | `--paranoid` (95%)

---
https://reasonkit.sh
EOF

	success_msg "Grok CLI integration installed"
}

install_opencode_skills() {
	info_msg "Installing OpenCode skills..."
	local skills_dir="$HOME/.opencode/skills/reasonkit"
	mkdir -p "$skills_dir"

	cat >"$skills_dir/SKILL.md" <<'EOF'
---
name: rk
description: ReasonKit structured reasoning protocols for OpenCode
---

# ReasonKit for OpenCode

## Quick Start
```bash
opencode "Apply ReasonKit --paranoid to: your question"
opencode "your question" | rk think --balanced
```

## Profiles
- `--quick` (70%) | `--balanced` (80%) | `--deep` (85%) | `--paranoid` (95%)

---
https://reasonkit.sh
EOF

	success_msg "OpenCode skills installed"
}

install_copilot_integration() {
	info_msg "Installing GitHub Copilot CLI integration..."

	echo ""
	info_msg "Copilot integration via CLI:"
	echo "  gh copilot suggest 'task' | rk think --quick"
	echo "  gh copilot explain 'code' | rk think --balanced"
	echo ""

	success_msg "Copilot integration notes displayed"
}

install_web() {
	info_msg "Installing reasonkit-web (web sensing layer)..."

	if command -v uv >/dev/null 2>&1; then
		progress_start "Installing with uv..."
		if uv pip install reasonkit-web 2>/dev/null; then
			progress_done
		else
			progress_fail
			warn_msg "reasonkit-web not yet on PyPI"
		fi
	elif command -v pip >/dev/null 2>&1; then
		warn_msg "Using pip (consider installing uv for faster installs)"
		progress_start "Installing with pip..."
		pip install reasonkit-web 2>/dev/null || {
			progress_fail
			warn_msg "reasonkit-web not yet on PyPI"
		}
	else
		warn_msg "Python not found. Skip reasonkit-web."
	fi
}

# ============================================================
# PATH Setup
# ============================================================
setup_path() {
	if [[ ":$PATH:" == *":$BIN_DIR:"* ]]; then
		return
	fi

	echo ""
	warn_msg "$BIN_DIR is not in your PATH"

	if [ "${RK_NO_MODIFY_PATH:-0}" = "1" ] || $NON_INTERACTIVE; then
		show_path_instructions
		return
	fi

	local shell_name shell_rc
	shell_name=$(basename "$SHELL")
	case "$shell_name" in
	bash) shell_rc="$HOME/.bashrc" ;;
	zsh) shell_rc="$HOME/.zshrc" ;;
	fish) shell_rc="$HOME/.config/fish/config.fish" ;;
	*) shell_rc="" ;;
	esac

	if [ -n "$shell_rc" ]; then
		if ask_yes_no "Add $BIN_DIR to PATH in $shell_rc?"; then
			echo "" >>"$shell_rc"
			echo "# ReasonKit" >>"$shell_rc"
			echo "export PATH=\"\$PATH:$BIN_DIR\"" >>"$shell_rc"
			success_msg "PATH updated in $shell_rc"
			info_msg "Run 'source $shell_rc' or restart your terminal"
		else
			show_path_instructions
		fi
	else
		show_path_instructions
	fi
}

show_path_instructions() {
	info_msg "Add to your shell config:"
	echo "  export PATH=\"\$PATH:$BIN_DIR\""
}

# ============================================================
# Verification
# ============================================================
verify_installation() {
	local binary="${1:-}"

	$SKIP_VERIFY && return 0

	echo ""
	info_msg "Verifying installation..."

	if [ -z "$binary" ]; then
		for bin_path in "$BIN_DIR/rk" "$BIN_DIR/rk-core" "$HOME/.cargo/bin/rk"; do
			[ -x "$bin_path" ] && binary="$bin_path" && break
		done
	fi

	[ -z "$binary" ] && command -v rk >/dev/null 2>&1 && binary=$(command -v rk)

	if [ -z "$binary" ] || [ ! -x "$binary" ]; then
		error_msg "Binary not found"
		return 1
	fi

	progress_start "Checking rk --version..."
	local version_output
	if version_output=$("$binary" --version 2>&1); then
		progress_done
		success_msg "Version: $version_output"
	else
		progress_fail
		error_msg "Failed to run rk --version"
		return 1
	fi

	success_msg "Installation verified successfully!"
}

# ============================================================
# Interactive Wizard (Simple Yes/No Questions)
# ============================================================
run_interactive_wizard() {
	echo ""
	echo -e "${BOLD}╔═══════════════════════════════════════════════════════════╗${NC}"
	echo -e "${BOLD}║          ReasonKit Installation Wizard                     ║${NC}"
	echo -e "${BOLD}╚═══════════════════════════════════════════════════════════╝${NC}"
	echo ""

	# Show detected tools
	if [ ${#DETECTED_TOOLS[@]} -gt 0 ]; then
		echo -e "${CYAN}Detected AI tools:${NC} ${DETECTED_TOOLS[*]}"
		echo ""
	fi

	# Ask simple questions
	echo -e "${BOLD}Optional components:${NC}"
	echo ""

	# Memory features
	if ask_yes_no "Include memory features (RAG, vector search, knowledge base)?"; then
		WITH_MEMORY=true
	fi

	# Web features
	if ask_yes_no "Include web sensing (source triangulation, browser automation)?"; then
		WITH_WEB=true
	fi

	# MCP Server
	if ask_yes_no "Configure MCP Server (for Claude Desktop)?"; then
		WITH_MCP=true
	fi

	# Claude Code integration
	if [[ " ${DETECTED_TOOLS[*]} " =~ " claude " ]] || ask_yes_no "Install Claude Code commands (/rk-* slash commands)?"; then
		WITH_COMMANDS=true
		WITH_SKILLS=true
	fi

	# Other tool integrations
	for tool in "${DETECTED_TOOLS[@]}"; do
		case $tool in
		codex)
			ask_yes_no "Install Codex CLI skills?" && WITH_SKILLS=true
			;;
		gemini)
			ask_yes_no "Install Gemini CLI integration?" && WITH_SKILLS=true
			;;
		grok)
			ask_yes_no "Install Grok CLI integration?" && WITH_SKILLS=true
			;;
		opencode)
			ask_yes_no "Install OpenCode skills?" && WITH_SKILLS=true
			;;
		copilot)
			ask_yes_no "Show GitHub Copilot integration tips?" && WITH_SKILLS=true
			;;
		esac
	done

	echo ""
}

# ============================================================
# Post-Install Summary
# ============================================================
show_summary() {
	local installed_components="Core CLI"
	$WITH_WEB && installed_components="$installed_components, Web"
	$WITH_MEMORY && installed_components="$installed_components, Memory"
	$WITH_MCP && installed_components="$installed_components, MCP"
	$WITH_SKILLS && installed_components="$installed_components, Skills"
	$WITH_COMMANDS && installed_components="$installed_components, Commands"

	echo ""
	echo -e "${GREEN}╔═══════════════════════════════════════════════════════════╗${NC}"
	echo -e "${GREEN}║${NC} ${BOLD}SUCCESS${NC} ReasonKit installed!                              ${GREEN}║${NC}"
	echo -e "${GREEN}╠═══════════════════════════════════════════════════════════╣${NC}"
	echo -e "${GREEN}║${NC} ${CYAN}Installed:${NC} $installed_components"
	echo -e "${GREEN}║${NC}"
	if [ ${#DETECTED_TOOLS[@]} -gt 0 ]; then
		echo -e "${GREEN}║${NC} ${CYAN}AI Tools:${NC} ${DETECTED_TOOLS[*]}"
		echo -e "${GREEN}║${NC}"
	fi
	echo -e "${GREEN}║${NC} ${BOLD}Quick Start:${NC}"
	echo -e "${GREEN}║${NC}   rk think --quick \"your question\""
	echo -e "${GREEN}║${NC}   rk think --paranoid \"critical analysis\""
	if $WITH_COMMANDS; then
		echo -e "${GREEN}║${NC}"
		echo -e "${GREEN}║${NC} ${BOLD}Claude Code:${NC}"
		echo -e "${GREEN}║${NC}   /rk-help    - See all commands"
		echo -e "${GREEN}║${NC}   /rk-think   - Deep analysis"
		echo -e "${GREEN}║${NC}   /rk-decide  - Decision protocol"
	fi
	echo -e "${GREEN}║${NC}"
	echo -e "${GREEN}║${NC} ${DIM}Docs: https://reasonkit.sh/docs${NC}"
	echo -e "${GREEN}╚═══════════════════════════════════════════════════════════╝${NC}"
	echo ""
}

# ============================================================
# Parse Arguments
# ============================================================
parse_args() {
	while [[ $# -gt 0 ]]; do
		case $1 in
		-y | --yes | --non-interactive)
			NON_INTERACTIVE=true
			;;
		--full | -f)
			FULL_INSTALL=true
			WITH_MCP=true
			WITH_SKILLS=true
			WITH_COMMANDS=true
			WITH_MEMORY=true
			WITH_WEB=true
			;;
		--with-mcp) WITH_MCP=true ;;
		--with-skills) WITH_SKILLS=true ;;
		--with-commands) WITH_COMMANDS=true ;;
		--with-memory) WITH_MEMORY=true ;;
		--with-web) WITH_WEB=true ;;
		--quiet | -q)
			QUIET=true
			NON_INTERACTIVE=true
			;;
		--force | -F) FORCE=true ;;
		--skip-verify) SKIP_VERIFY=true ;;
		--debug) DEBUG=1 ;;
		--version | -v)
			echo "ReasonKit Installer v$INSTALLER_VERSION"
			exit 0
			;;
		--help | -h)
			cat <<HELPEOF
ReasonKit Installer v$INSTALLER_VERSION

USAGE:
    curl -fsSL https://get.reasonkit.sh | bash
    curl -fsSL https://get.reasonkit.sh | bash -s -- [OPTIONS]

OPTIONS:
    -y, --yes             Non-interactive mode (default: interactive)
    -f, --full            Install all components
    --with-web            Include web sensing (reasonkit-web)
    --with-memory         Include RAG, vector search, knowledge base
    --with-mcp            Include MCP server configuration
    --with-skills         Include Claude/Codex/OpenCode skills
    --with-commands       Include Claude Code /rk-* commands
    -q, --quiet           Minimal output (implies -y)
    -F, --force           Force reinstall without prompts
    --skip-verify         Skip post-install verification
    --debug               Enable debug output
    -v, --version         Show installer version
    -h, --help            Show this help message

EXAMPLES:
    # Interactive installation (default)
    curl -fsSL https://get.reasonkit.sh | bash

    # Non-interactive for CI/CD
    curl -fsSL https://get.reasonkit.sh | bash -s -- -y

    # Full installation with everything
    curl -fsSL https://get.reasonkit.sh | bash -s -- --full -y

    # Custom selection
    curl -fsSL https://get.reasonkit.sh | bash -s -- --with-memory --with-commands -y

HELPEOF
			exit 0
			;;
		*)
			error_msg "Unknown option: $1"
			exit 1
			;;
		esac
		shift
	done
}

# ============================================================
# Main
# ============================================================
main() {
	setup_colors
	parse_args "$@"

	if ! $QUIET; then
		banner
	fi

	check_dependencies
	mkdir -p "$INSTALL_DIR" "$BIN_DIR"
	check_existing_installation
	detect_tools

	# Run interactive wizard if not in non-interactive mode and no flags set
	if ! $NON_INTERACTIVE && ! $FULL_INSTALL && ! $WITH_MCP && ! $WITH_SKILLS && ! $WITH_COMMANDS && ! $WITH_MEMORY && ! $WITH_WEB; then
		run_interactive_wizard
	fi

	# Install core (always)
	install_core

	# Install optional components
	$WITH_WEB && install_web
	$WITH_MCP && install_mcp

	# Claude Code integration
	if $WITH_COMMANDS; then
		install_claude_commands
	fi
	if $WITH_SKILLS; then
		install_claude_skills

		# Install skills for other detected tools
		for tool in "${DETECTED_TOOLS[@]}"; do
			case $tool in
			codex) install_codex_skills ;;
			gemini) install_gemini_integration ;;
			grok) install_grok_integration ;;
			opencode) install_opencode_skills ;;
			copilot) install_copilot_integration ;;
			esac
		done
	fi

	# Setup PATH
	setup_path

	# Verify installation
	verify_installation

	# Show summary
	if ! $QUIET; then
		banner
		show_summary
	fi
}

main "$@"
