#!/usr/bin/env bash
# phoneide official installer
# Usage:
#   curl -fsSL https://phoneide.samai.cc/install.sh | bash
#   curl -fsSL https://phoneide.samai.cc/install.sh | bash -s -- --version 1.2.11
#
# Installs PhoneIDE ¡ª the lightweight mobile Web IDE.
# Downloads a standalone binary (preferred) or falls back to wheel install in a venv.
# No source code is shipped; no git clone is performed.

set -euo pipefail

# ---- defaults -------------------------------------------------------------
BASE_URL="https://phoneide.samai.cc/downloads"
INSTALL_DIR="/usr/local/bin"
BIN_NAME="phoneide"
REQUESTED_VERSION=""

# ---- parse args -----------------------------------------------------------
while [[ $# -gt 0 ]]; do
    case "$1" in
        --version) REQUESTED_VERSION="$2"; shift 2 ;;
        --help|-h)
            echo "phoneide installer"
            echo "  curl -fsSL https://phoneide.samai.cc/install.sh | bash"
            exit 0 ;;
        *) echo "Unknown option: $1" >&2; exit 1 ;;
    esac
done

# ---- helpers --------------------------------------------------------------
info()  { printf '[OK] %s\n' "$*"; }
warn()  { printf '[!] %s\n' "$*" >&2; }
error() { printf '[X] %s\n' "$*" >&2; }
die()   { error "$*"; exit 1; }

# ---- detect OS / arch -----------------------------------------------------
OS="$(uname -s)"
ARCH="$(uname -m)"
case "$OS" in
    Linux*)  PLATFORM_OS="linux" ;;
    Darwin*) PLATFORM_OS="darwin" ;;
    MINGW*|MSYS*|CYGWIN*)
        die "Windows detected. Run in PowerShell: irm https://phoneide.samai.cc/install.ps1 | iex" ;;
    *) die "Unsupported OS: $OS" ;;
esac
case "$ARCH" in
    x86_64|amd64)   PLATFORM_ARCH="amd64" ;;
    aarch64|arm64)  PLATFORM_ARCH="arm64" ;;
    *) die "Unsupported architecture: $ARCH" ;;
esac

PLATFORM="${PLATFORM_OS}-${PLATFORM_ARCH}"
info "Detected platform: $PLATFORM"

# Termux detection (install to $PREFIX/bin if writable)
TERMUX_MODE=false
if [[ -n "${TERMUX_VERSION:-}" ]] || [[ -d "/data/data/com.termux" && "${PLATFORM_OS}" == "linux" ]]; then
    if [[ -d "${PREFIX:-/data/data/com.termux/files/usr}" && -w "${PREFIX:-/data/data/com.termux/files/usr}/bin" ]]; then
        TERMUX_MODE=true
        INSTALL_DIR="${PREFIX}/bin"
        info "Termux detected, install dir: $INSTALL_DIR"
    fi
fi

# ---- pick install dir (sudo or not) --------------------------------------
SUDO=""
if [[ -w "$INSTALL_DIR" ]]; then
    TARGET="${INSTALL_DIR}/${BIN_NAME}"
elif command -v sudo >/dev/null 2>&1 && sudo -n true 2>/dev/null; then
    TARGET="${INSTALL_DIR}/${BIN_NAME}"
    SUDO="sudo"
else
    TARGET="${HOME}/.local/bin/${BIN_NAME}"
    mkdir -p "$(dirname "$TARGET")"
    warn "No sudo access - installing to $TARGET"
fi

# ---- pick version ---------------------------------------------------------
if [[ -z "$REQUESTED_VERSION" ]]; then
    info "Fetching latest version from $BASE_URL/latest-version.txt ..."
    REQUESTED_VERSION="$(curl -fsSL "$BASE_URL/latest-version.txt" | tr -d '[:space:]' || true)"
    [[ -z "$REQUESTED_VERSION" ]] && die "Could not determine latest version."
fi
info "Installing phoneide v$REQUESTED_VERSION"

# ---- detect Python (fallback for wheel method) ----------------------------
PY_CMD=""
for cmd in python3.14 python3.13 python3.12 python3.11 python3.10 python3.8 python3 python; do
    if command -v "$cmd" &>/dev/null; then
        ver="$($cmd -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")' 2>/dev/null)" || continue
        major="$(echo "$ver" | cut -d. -f1)"
        minor="$(echo "$ver" | cut -d. -f2)"
        if [[ "$major" -eq 3 ]] && [[ "$minor" -ge 8 ]]; then
            PY_CMD="$cmd"; break
        fi
    fi
done

# ---- phoneide runtime directory -------------------------------------------
PHONEIDE_RUNTIME="${HOME}/.phoneide/runtime"
VENV_DIR="${PHONEIDE_RUNTIME}/venv"
mkdir -p "$PHONEIDE_RUNTIME"

# ---- download strategy: try standalone binary first, fallback to wheel ----
TMP_FILE="$(mktemp -t phoneide-XXXXXX)"
trap 'rm -f "$TMP_FILE"' EXIT

BINARY_FILE="phoneide-${PLATFORM}"
BINARY_URL="$BASE_URL/$BINARY_FILE"
BINARY_AVAILABLE=false

info "Checking for standalone binary: $BINARY_FILE ..."
if curl -fsSL --head "$BINARY_URL" 2>/dev/null | grep -q "200"; then
    BINARY_AVAILABLE=true
fi

if $BINARY_AVAILABLE; then
    info "Downloading standalone binary $BINARY_URL ..."
    if ! curl -fSL --retry 3 --retry-delay 2 -o "$TMP_FILE" "$BINARY_URL"; then
        die "Download failed."
    fi

    info "Verifying SHA256 checksum ..."
    EXPECTED_HASH="$(curl -fsSL "$BASE_URL/checksums-sha256.txt" 2>/dev/null | awk -v f="$BINARY_FILE" '$2==f {print $1; exit}' || true)"
    if [[ -n "$EXPECTED_HASH" ]]; then
        ACTUAL_HASH="$(sha256sum "$TMP_FILE" | awk '{print $1}')"
        if [[ "$EXPECTED_HASH" != "$ACTUAL_HASH" ]]; then
            die "Checksum mismatch! expected: $EXPECTED_HASH actual: $ACTUAL_HASH"
        fi
        info "Checksum OK"
    else
        warn "No checksum entry for $BINARY_FILE - skipping verification."
    fi

    info "Installing to $TARGET ..."
    if [[ -n "$SUDO" ]]; then
        $SUDO install -m 0755 "$TMP_FILE" "$TARGET"
    else
        install -m 0755 "$TMP_FILE" "$TARGET"
    fi
else
    # No standalone binary for this platform - use wheel method
    info "No standalone binary for $PLATFORM, using wheel method ..."
    if [[ -z "$PY_CMD" ]]; then
        die "Python 3.8+ is required for this platform. Install Python first:
  Ubuntu/Debian: sudo apt install python3 python3-venv
  Termux:        pkg install python
  macOS:         brew install python3"
    fi

    if [[ ! -d "$VENV_DIR" ]]; then
        info "Creating Python virtual environment ..."
        "$PY_CMD" -m venv "$VENV_DIR" 2>/dev/null || "$PY_CMD" -m venv --without-pip "$VENV_DIR"
    fi

    # Bootstrap pip if missing (some --without-pip venvs)
    if [[ ! -x "$VENV_DIR/bin/pip" ]]; then
        info "Bootstrapping pip in venv ..."
        curl -fsSL https://bootstrap.pypa.io/get-pip.py -o "$TMP_FILE.getpip" 2>/dev/null || true
        if [[ -f "$TMP_FILE.getpip" ]]; then
            "$VENV_DIR/bin/python" "$TMP_FILE.getpip" --quiet 2>/dev/null || true
            rm -f "$TMP_FILE.getpip"
        fi
    fi

    # Download wheel from phoneide.samai.cc (NOT PyPI), fallback to PyPI
    info "Looking for compatible wheel from $BASE_URL ..."
    WHL_NAME="$(curl -fsSL "$BASE_URL/" 2>/dev/null | grep -oE 'phoneide-[0-9][^"]*\.whl' | head -1 || true)"

    if [[ -n "$WHL_NAME" ]]; then
        info "Found wheel: $WHL_NAME"
        if curl -fSL --retry 3 --retry-delay 2 -o "$TMP_FILE" "$BASE_URL/$WHL_NAME"; then
            info "Installing wheel locally (from phoneide.samai.cc) ..."
            "$VENV_DIR/bin/pip" install --upgrade "$TMP_FILE" 2>/dev/null || \
            "$VENV_DIR/bin/pip" install --no-deps "$TMP_FILE" 2>/dev/null || \
            warn "Wheel install failed"
        fi
    else
        info "No wheel on phoneide.samai.cc, falling back to PyPI ..."
        "$VENV_DIR/bin/pip" install "phoneide==$REQUESTED_VERSION" 2>/dev/null || \
        "$VENV_DIR/bin/pip" install phoneide 2>/dev/null || \
        warn "Wheel install from PyPI failed"
    fi

    # Create launcher script
    LAUNCHER="${TARGET}"
    info "Creating launcher at $LAUNCHER ..."
    LAUNCHER_DIR="$(dirname "$LAUNCHER")"
    mkdir -p "$LAUNCHER_DIR" 2>/dev/null || true
    cat > "$LAUNCHER" << 'LAUNCHER_EOF'
#!/usr/bin/env bash
exec ~/.phoneide/runtime/venv/bin/phoneide "$@"
LAUNCHER_EOF
    # If the console-script wasn't installed (no-deps case), call python -m
    if [[ ! -x "$VENV_DIR/bin/phoneide" ]]; then
        cat > "$LAUNCHER" << 'LAUNCHER_EOF'
#!/usr/bin/env bash
exec ~/.phoneide/runtime/venv/bin/python -m phoneide_server "$@"
LAUNCHER_EOF
    fi
    chmod 755 "$LAUNCHER"
fi

# ---- macOS quarantine notice ---------------------------------------------
if [[ "$PLATFORM_OS" == "darwin" ]]; then
    if command -v xattr >/dev/null 2>&1; then
        xattr -d com.apple.quarantine "$TARGET" 2>/dev/null || true
    fi
    warn "On macOS you may need to allow the binary in System Settings > Privacy & Security."
fi

# ---- PATH hint ------------------------------------------------------------
case ":$PATH:" in
    *":$(dirname "$TARGET"):"*) ;;
    *)
        warn "$(dirname "$TARGET") is not in your PATH."
        warn "Add: export PATH=\"$(dirname "$TARGET"):\$PATH\"" ;;
esac

echo
info "Done! Try it now:"
echo "    phoneide              # start PhoneIDE (default port 12345)"
echo "    phoneide --port 8080  # start on a custom port"
echo
info "Docs: https://phoneide.samai.cc   |   Releases: https://phoneide.samai.cc/downloads/"
