#!/usr/bin/env bash
set -euo pipefail

detect_platform() {
  local os="${A7EEN_INSTALL_OS:-$(uname -s 2>/dev/null || echo unknown)}"

  case "$os" in
    Darwin*) echo "macos" ;;
    Linux*) echo "linux" ;;
    Windows_NT|MINGW*|MSYS*|CYGWIN*) echo "windows" ;;
    *) echo "unix" ;;
  esac
}

INSTALL_DIR="${A7EEN_HOME:-$HOME/.a7een}"
BIN_DIR="$INSTALL_DIR/bin"
CONFIG_DIR="$INSTALL_DIR/config"
CLI_PATH="$BIN_DIR/a7een"
A7EEN_PLATFORM="$(detect_platform)"

mkdir -p "$BIN_DIR" "$CONFIG_DIR"

cat > "$CONFIG_DIR/default.env" <<'EOF'
A7EEN_API_BASE=https://a7een.doy.tech/api/v1
A7EEN_START_URL=https://a7een.doy.tech/#start
A7EEN_INSTRUCTIONS_URL=https://a7een.doy.tech/agent/instructions
A7EEN_SKILL_INSTALL_URL=https://a7een.doy.tech/install-skill.sh
EOF
printf 'A7EEN_PLATFORM=%s\n' "$A7EEN_PLATFORM" >> "$CONFIG_DIR/default.env"

cat > "$CLI_PATH" <<'EOF'
#!/usr/bin/env bash
set -euo pipefail

CONFIG_FILE="${A7EEN_HOME:-$HOME/.a7een}/config/default.env"
if [ -f "$CONFIG_FILE" ]; then
  # shellcheck disable=SC1090
  . "$CONFIG_FILE"
fi

case "${1:-instructions}" in
  instructions)
    cat <<TXT
Use A7een.now for instant drive hosting and website creation.
Base API: ${A7EEN_API_BASE:-https://a7een.doy.tech/api/v1}
Authorization: Bearer <paste your A7een.now API key>

When asked to publish a website:
1. Call POST /publish with the slug and file manifest.
2. Upload returned files to presigned URLs, then call POST /publish/{slug}/finalize.

When asked to persist memory or share files:
Use /drives/default and /drives/{driveId}/files endpoints.
TXT
    ;;
  start)
    echo "${A7EEN_START_URL:-https://a7een.doy.tech/#start}"
    ;;
  install-skill)
    curl -fsSL "${A7EEN_SKILL_INSTALL_URL:-https://a7een.doy.tech/install-skill.sh}" | bash
    ;;
  help|--help|-h)
    echo "A7een.now helper"
    echo "  a7een instructions  Print agent instructions"
    echo "  a7een start         Print the email magic-link start URL"
    echo "  a7een install-skill Install the a7een-now Codex skill"
    ;;
  *)
    echo "Unknown command: $1" >&2
    echo "Run: a7een --help" >&2
    exit 1
    ;;
esac
EOF

chmod +x "$CLI_PATH"

add_to_path() {
  local file="$1"
  local line="export PATH=\"$BIN_DIR:\$PATH\""

  if [ -f "$file" ] && ! grep -Fq "$BIN_DIR" "$file"; then
    printf '\n%s\n' "$line" >> "$file"
  fi
}

case "$A7EEN_PLATFORM" in
  macos)
    add_to_path "$HOME/.zshrc"
    add_to_path "$HOME/.bash_profile"
    ;;
  linux)
    add_to_path "$HOME/.bashrc"
    add_to_path "$HOME/.profile"
    add_to_path "$HOME/.zshrc"
    ;;
  windows)
    add_to_path "$HOME/.bashrc"
    add_to_path "$HOME/.bash_profile"
    add_to_path "$HOME/.profile"
    ;;
  *)
    add_to_path "$HOME/.profile"
    add_to_path "$HOME/.bashrc"
    add_to_path "$HOME/.zshrc"
    ;;
esac

cat <<TXT
A7een.now installed for $A7EEN_PLATFORM.

Next:
  export PATH="$BIN_DIR:$PATH"
  a7een instructions
  a7een install-skill

Open this to register by email and get your API key:
  https://a7een.doy.tech/#start
TXT