#!/bin/bash
# IKKF CLI — self-contained installer (macOS / Linux)
# Free-core: no license, no key required.
#
# Usage:
#   curl -fsSL https://ikkf.info/install.sh | bash
#   bash <(curl -fsSL https://ikkf.info/install.sh)
set -e

VERSION="3.6.1"
# Base URL for the package. Defaults to the live site. For local testing:
#   IKKF_BASE_URL=http://localhost:3000 curl -fsSL http://localhost:3000/install.sh | bash
BASE_URL="${IKKF_BASE_URL:-https://ikkf.info}"
PKG_URL="$BASE_URL/ikkf-cli.zip"

INSTALL_ROOT="$HOME/.local/share/ikkf-cli"
VENV_DIR="$INSTALL_ROOT/venv"
PKG_DIR="$INSTALL_ROOT/ikkf"
BIN_DIR="$HOME/.local/bin"
WRAPPER="$BIN_DIR/ikkf"

# Colors
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; CYAN='\033[0;36m'; NC='\033[0m'

echo -e "${CYAN}🚀 Installing IKKF CLI v$VERSION (free-core)...${NC}"

# 1. Python pre-flight (hard gate on 3.10+; IKKF needs it)
if ! command -v python3 &>/dev/null; then
    echo -e "${RED}✘ Python 3 not found. Install Python 3.10+ (e.g. 'brew install python').${NC}"
    exit 1
fi
PY_VER=$(python3 -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")')
PY_MAJOR=$(echo "$PY_VER" | cut -d. -f1)
PY_MINOR=$(echo "$PY_VER" | cut -d. -f2)
if [ "$PY_MAJOR" -lt 3 ] || { [ "$PY_MAJOR" -eq 3 ] && [ "$PY_MINOR" -lt 10 ]; }; then
    echo -e "${RED}✘ IKKF requires Python 3.10 or newer; found $PY_VER. Upgrade Python (e.g. 'brew install python') and re-run.${NC}"
    exit 1
fi
echo -e "${GREEN}✓ Python $PY_VER detected (3.10+ required).${NC}"

# 1b. Ensure python3 can create a venv and pip is present (some minimal distros lack these)
if ! python3 -m venv --help >/dev/null 2>&1; then
    echo -e "${RED}✘ python3 cannot create venvs. On Debian/Ubuntu install 'python3-venv' and 'python3-pip', then re-run.${NC}"
    exit 1
fi
if ! python3 -m pip --version >/dev/null 2>&1; then
    echo -e "${RED}✘ python3 pip is missing. Install 'python3-pip' (or ensure pip is available), then re-run.${NC}"
    exit 1
fi

# 2. Download package
echo -e "${CYAN}Downloading IKKF package from $PKG_URL...${NC}"
TMP_ZIP=$(mktemp -d)/ikkf.zip
if command -v curl &>/dev/null; then
    curl -fsSL "$PKG_URL" -o "$TMP_ZIP" || { echo -e "${RED}✘ Could not download $PKG_URL${NC}"; echo -e "${YELLOW}  If testing locally, set IKKF_BASE_URL to your server, e.g.:${NC}"; echo -e "  IKKF_BASE_URL=http://localhost:3000 curl -fsSL http://localhost:3000/install.sh | bash"; exit 1; }
elif command -v wget &>/dev/null; then
    wget -q "$PKG_URL" -O "$TMP_ZIP" || { echo -e "${RED}✘ Could not download $PKG_URL${NC}"; exit 1; }
else
    echo -e "${RED}✘ Neither curl nor wget found.${NC}"; exit 1
fi

# 2b. Verify integrity (SHA256) — fail closed if the download is tampered/mismatched
# Update IKKF_SHA256 whenever ikkf-cli.zip changes.
EXPECTED_SHA="7ae0974799a5d68edac157413c7f67b03a126834c5fd6c2eb0e0d1afceb3dcb6"
ACTUAL_SHA=$(shasum -a 256 "$TMP_ZIP" 2>/dev/null | awk '{print $1}')
if [ -z "$ACTUAL_SHA" ]; then
    ACTUAL_SHA=$(sha256sum "$TMP_ZIP" 2>/dev/null | awk '{print $1}')
fi
if [ "$ACTUAL_SHA" != "$EXPECTED_SHA" ]; then
    echo -e "${RED}✘ Integrity check FAILED.\n  expected: $EXPECTED_SHA\n  got:      ${ACTUAL_SHA:-none}\n  The download may be tampered with or corrupted. Aborting.${NC}"
    exit 1
fi

echo -e "${GREEN}✓ Package verified (SHA256).${NC}"

# 3. Deploy source
echo -e "${CYAN}Deploying to $INSTALL_ROOT...${NC}"
mkdir -p "$INSTALL_ROOT"
rm -rf "$PKG_DIR"
if command -v unzip &>/dev/null; then
    unzip -q "$TMP_ZIP" -d "$INSTALL_ROOT"
else
    python3 -c "import zipfile,sys; zipfile.ZipFile(sys.argv[1]).extractall('$INSTALL_ROOT')" "$TMP_ZIP"
fi
rm -f "$TMP_ZIP"
if [ ! -d "$PKG_DIR" ]; then
    echo -e "${RED}✘ Package extraction failed (no ikkf/ dir).${NC}"; exit 1
fi
echo -e "${GREEN}✓ Source deployed.${NC}"

# 4. Venv + deps
echo -e "${CYAN}Creating venv and installing dependencies...${NC}"
rm -rf "$VENV_DIR"
python3 -m venv "$VENV_DIR"
"$VENV_DIR/bin/python3" -m pip install --upgrade pip -q
"$VENV_DIR/bin/python3" -m pip install -q "typer==0.25.1" "rich==15.0.0" "pyyaml==6.0.3" "pydantic==2.13.4" "requests==2.34.2" "cryptography==48.0.0"
echo -e "${GREEN}✓ Dependencies installed.${NC}"

# 5. Wrapper
echo -e "${CYAN}Creating 'ikkf' command...${NC}"
mkdir -p "$BIN_DIR"
cat > "$WRAPPER" <<EOF
#!/bin/bash
# IKKF CLI wrapper (v$VERSION)
export PYTHONPATH="$INSTALL_ROOT"
exec "$VENV_DIR/bin/python3" -m ikkf "\$@"
EOF
chmod +x "$WRAPPER"
echo -e "${GREEN}✓ Created $WRAPPER${NC}"

# 6. PATH
if [[ ":$PATH:" != *":$BIN_DIR:"* ]]; then
    SHELL_CONFIG=""
    [ -n "$ZSH_VERSION" ] && SHELL_CONFIG="$HOME/.zshrc"
    [ -n "$BASH_VERSION" ] && SHELL_CONFIG="$HOME/.bashrc"
    [ -z "$SHELL_CONFIG" ] && SHELL_CONFIG="$HOME/.profile"
    if [ -f "$SHELL_CONFIG" ]; then
        echo "" >> "$SHELL_CONFIG"
        echo "# IKKF CLI" >> "$SHELL_CONFIG"
        echo "export PATH=\"$BIN_DIR:\$PATH\"" >> "$SHELL_CONFIG"
        echo -e "${YELLOW}⚠ Added $BIN_DIR to PATH in $SHELL_CONFIG. Run 'source $SHELL_CONFIG'.${NC}"
    else
        echo -e "${YELLOW}⚠ Add $BIN_DIR to your PATH manually.${NC}"
    fi
else
    echo -e "${GREEN}✓ $BIN_DIR already in PATH.${NC}"
fi

echo ""
echo -e "${GREEN}🎉 IKKF CLI v$VERSION installed successfully!${NC}"
echo ""
echo "Usage:"
echo "  ikkf init              # Initialize config"
echo "  ikkf start '<task>'    # Start a new task"
echo "  ikkf status            # Check tasks"
echo "  ikkf --help            # All commands"
echo ""
echo "Run 'source $SHELL_CONFIG' (or open a new terminal), then try: ikkf --help"
