#!/data/data/com.termux/files/usr/bin/bash
export AICODER_REF="v1.3.0"
# ai-coder Termux Installer
# curl -sL https://ailinux.me/ai-coder-termux | bash

# CWD fix — curl|bash hat kein gültiges Verzeichnis (Termux-Bug)
cd "${HOME:-/data/data/com.termux/files/home}" 2>/dev/null || cd /tmp

set -e

RED='\033[0;31m'; GREEN='\033[0;32m'; CYAN='\033[0;36m'; NC='\033[0m'

echo -e "${CYAN}"
echo "╔══════════════════════════════════════╗"
echo "║   ai-coder — Termux Installer        ║"
echo "║   AILinux Agent für Android          ║"
echo "╚══════════════════════════════════════╝"
echo -e "${NC}"

# Deps installieren
echo -e "${CYAN}[1/4] Pakete installieren...${NC}"
pkg update -y -q
pkg install -y python git curl openssl-tool

# ai-coder deps (kein pip upgrade — kaputt in Termux)
echo -e "${CYAN}[2/4] Python-Deps installieren...${NC}"
PYTHONPATH="" pip3 install --quiet httpx rich typer certifi urllib3 markdown prompt-toolkit 2>/dev/null || \
  PYTHONPATH="" pip install --quiet httpx rich typer certifi urllib3 markdown prompt-toolkit

echo -e "${CYAN}[3/4] ai-coder holen...${NC}" 

# Source von GitHub holen
INSTALL_DIR="$HOME/.local/lib/aicoder-src"
rm -rf "$INSTALL_DIR"
AICODER_REF="${AICODER_REF:-master}"
git clone --depth=1 --branch "$AICODER_REF" -q \
  https://github.com/derleiti/ai-coder.git "$INSTALL_DIR"

# Wrapper-Script
mkdir -p "$HOME/.local/bin"
cat > "$HOME/.local/bin/aicoder" << 'WRAPPER'
#!/data/data/com.termux/files/usr/bin/bash
# CWD fix — Python crasht wenn getcwd() fehlschlägt
cd "${HOME:-/data/data/com.termux/files/home}" 2>/dev/null || cd /tmp
export PYTHONPATH="$HOME/.local/lib/aicoder-src:$PYTHONPATH"
exec python3 -m aicoder "$@"
WRAPPER
chmod +x "$HOME/.local/bin/aicoder"

# PATH sicherstellen
if ! grep -q 'local/bin' "$HOME/.bashrc" 2>/dev/null; then
    echo 'export PATH="$HOME/.local/bin:$PATH"' >> "$HOME/.bashrc"
fi

echo -e "${CYAN}[4/4] Fertig!${NC}"
echo ""
echo -e "${GREEN}✓ ai-coder installiert!${NC}"
echo ""
echo "  Starten:"
echo "    source ~/.bashrc"
echo "    aicoder"
echo ""
echo "  Oder direkt:"
echo "    $HOME/.local/bin/aicoder"
echo ""
echo -e "${CYAN}  Backend: https://api.ailinux.me${NC}"
echo -e "${CYAN}  Beta-Code: AILINUX2026${NC}"
