#!/bin/sh
# yourspace.sh — single-file shell CLI (design preview)
# Usage: yourspace <login|init|deploy|ls|status|help>

set -eu

CONFIG_DIR="${YOURSPACE_DIR:-$HOME/.yourspace}"
TOKEN_FILE="$CONFIG_DIR/token"
API="https://api.yo.urspace.net"

log()  { printf '  \033[1;32m✓\033[0m %s\n' "$1"; }
warn() { printf '  \033[1;33m!\033[0m %s\n' "$1" >&2; }
err()  { printf '  \033[1;31m✗\033[0m %s\n' "$1" >&2; exit 1; }
ask()  { printf '  %s ' "$1" >&2; read -r R; printf '%s' "$R"; }

load_token() {
  if [ -n "${YOURSPACE_TOKEN:-}" ]; then TOKEN="$YOURSPACE_TOKEN"; return; fi
  [ -f "$TOKEN_FILE" ] || err "not logged in — run 'yourspace login' first"
  TOKEN="$(cat "$TOKEN_FILE")"
}

# -----------------------------------------------------------------------------
# yourspace login  — one-time token setup
#   Final plan: device-code flow that opens the dashboard in a browser and
#   exchanges a short code for a bearer token.
#   Today (stub): paste a token minted manually at /tokens.
# -----------------------------------------------------------------------------
cmd_login() {
  mkdir -p "$CONFIG_DIR" && chmod 700 "$CONFIG_DIR"
  printf '  Mint a deploy token at %s/tokens, then paste it.\n' "$API"
  TOKEN="$(ask 'token:')"
  [ -n "$TOKEN" ] || err "no token provided"
  printf '%s' "$TOKEN" > "$TOKEN_FILE" && chmod 600 "$TOKEN_FILE"
  log "saved → $TOKEN_FILE"
}

# -----------------------------------------------------------------------------
# yourspace init  — interactive yourspace.yml walkthrough
#   Defaults the site name from $PWD so most users just hit enter. Probes the
#   API so name collisions surface here, not at deploy time. Asks which
#   directory to ship — most static builds emit to ./dist.
#   The native binary's 'init' also accepts --name/--dir/--force for
#   scripting; same YAML shape either way.
# -----------------------------------------------------------------------------
cmd_init() {
  [ -f yourspace.yml ] && err "yourspace.yml already exists (pass --force to overwrite)"
  load_token

  DEFAULT="$(basename "$PWD" | tr '[:upper:]' '[:lower:]' | tr -c 'a-z0-9-' -)"
  NAME="$(ask "site name [$DEFAULT]:")"
  NAME="${NAME:-$DEFAULT}"

  STATUS="$(curl -fsS -o /dev/null -w '%{http_code}' \
    -H "Authorization: Bearer $TOKEN" "$API/v1/sites/$NAME" || true)"
  case "$STATUS" in
    200) err "'$NAME' is taken — try another name" ;;
    404) log "'$NAME' is available" ;;
    *)   warn "could not check availability (HTTP $STATUS); continuing" ;;
  esac

  DIST="$(ask 'static output directory [dist]:')"
  DIST="${DIST:-dist}"

  cat > yourspace.yml <<YAML
name: $NAME
# build is the CLI-side namespace — the server ignores it entirely.
# Keeps the nested shape matching the native CLI so a yourspace.yml
# written by this script can be fed to the Go binary without changes.
build:
  dist: $DIST
# Point custom domains at the yo.urspace.net edge via DNS; the dashboard
# walks you through it.
# custom_domains:
#   - example.com
# domain_redirects:
#   - from: www.example.com
#     to: example.com
YAML
  log "yourspace.yml created (https://$NAME.yo.urspace.net once deployed)"
}

# -----------------------------------------------------------------------------
# yourspace deploy  — bundle $dist and POST it alongside the config
#   Idempotent: repeat deploys replace the bundle for this site name and
#   bump the version counter.
# -----------------------------------------------------------------------------
cmd_deploy() {
  [ -f yourspace.yml ] || err "no yourspace.yml — run 'yourspace init' first"
  load_token

  NAME="$(awk -F: '/^name:/ { gsub(/ /,"",$2); print $2 }' yourspace.yml)"
  # build.dist is nested under the client-side 'build:' block to match the
  # native CLI's contract. Enter the block on ^build:, leave on the
  # next unindented line, and pull the first dist: value inside.
  DIST="$(awk '
    /^build:/                                 { in_build = 1; next }
    /^[^[:space:]]/                            { in_build = 0 }
    in_build && /^[[:space:]]+dist:[[:space:]]*/ {
      sub(/^[[:space:]]+dist:[[:space:]]*/, "")
      sub(/[[:space:]]*#.*$/, "")
      print; exit
    }
  ' yourspace.yml)"
  DIST="${DIST:-dist}"

  [ -d "$DIST" ] || err "$DIST/ not found — build your site before deploying"

  tar -czf dist.tar.gz -C "$DIST" .
  curl -fsSL -X POST "$API/v1/sites" \
    -H "Authorization: Bearer $TOKEN" \
    -F "config=@yourspace.yml" \
    -F "bundle=@dist.tar.gz"

  log "live → https://$NAME.yo.urspace.net"
}

# yourspace ls — sites you own (name, version, node count, last deploy)
cmd_ls() {
  load_token
  curl -fsS "$API/v1/sites" -H "Authorization: Bearer $TOKEN"
}

# yourspace status [name] — one site's live state (defaults to the yml's name)
cmd_status() {
  load_token
  NAME="${1:-$(awk '/^name:/ {print $2; exit}' yourspace.yml)}"
  [ -n "$NAME" ] || { printf 'yourspace status: pass a site name or run from a project with yourspace.yml\n' >&2; exit 2; }
  curl -fsS "$API/v1/sites/$NAME" -H "Authorization: Bearer $TOKEN"
}

case "${1:-help}" in
  login)  cmd_login ;;
  init)   cmd_init ;;
  deploy) cmd_deploy ;;
  ls)     cmd_ls ;;
  status) shift; cmd_status "$@" ;;
  *)
    printf 'Usage: yourspace <login|init|deploy|ls|status>\n'
    ;;
esac
