#!/usr/bin/env bash
# autocut 터미널 명령 — 어느 폴더에서든 `autocut` 으로 켜고 끕니다.
# 설치할 때 ~/.local/bin/autocut 으로 복사되며, {{DIR}} 자리에 실제 설치 경로가 채워집니다.
set -euo pipefail
DIR="{{DIR}}"
[ -d "$DIR" ] || { echo "autocut 폴더를 찾을 수 없습니다: $DIR" >&2; exit 1; }
PORT_D="${PORT:-8787}"
alive() { curl -fsS --max-time 2 "http://127.0.0.1:$PORT_D/health" 2>/dev/null | grep -q '"app":"autocut"'; }

case "${1:-start}" in
  start|"")
    if alive; then echo "이미 켜져 있습니다 → http://localhost:$PORT_D"; else bash "$DIR/start.sh" --daemon; fi
    command -v open >/dev/null && open "http://localhost:$PORT_D" || true ;;
  stop)   bash "$DIR/stop.sh" ;;
  restart) bash "$DIR/stop.sh" >/dev/null 2>&1 || true; sleep 1; bash "$DIR/start.sh" --daemon ;;
  status)
    if alive; then
      curl -fsS "http://127.0.0.1:$PORT_D/health"; echo
      echo "폴더: $DIR"
    else echo "꺼져 있습니다. 'autocut' 으로 켜세요.  (폴더: $DIR)"; fi ;;
  share)  bash "$DIR/start.sh" --share ;;          # 무료 공개 주소(cloudflared) — 쓰고 나면 stop 으로 닫으세요
  open)   command -v open >/dev/null && open "http://localhost:$PORT_D" || echo "http://localhost:$PORT_D" ;;
  manual) command -v open >/dev/null && open "http://localhost:$PORT_D/manual" || echo "http://localhost:$PORT_D/manual" ;;
  dir)    echo "$DIR"; command -v open >/dev/null && open "$DIR" || true ;;
  jobs)   ls -t "$DIR/jobs" 2>/dev/null | head -10 ;;
  update)
    echo "최신 버전을 받아 이 폴더에 덮어씁니다: $DIR"
    AUTOCUT_DIR="$DIR" bash -c "$(curl -fsSL https://autocut-landing.vercel.app/mac.sh)" ;;
  version) cat "$DIR/VERSION" 2>/dev/null || echo "알 수 없음" ;;
  admin)                                        # 판매 어드민 (판매자 폴더에만 있음)
    [ -f "$DIR/admin_store.py" ] || { echo "이 폴더에는 판매 어드민이 없습니다."; exit 1; }
    alive || bash "$DIR/start.sh" --daemon
    TOK="$(cat "$DIR/.autocut/admin_token" 2>/dev/null)"
    if [ -z "$TOK" ]; then
      TOK="$("$DIR/.venv/bin/python" -c "import sys;sys.path.insert(0,'$DIR');import admin_store;print(admin_store.token())")"
    fi
    URL="http://localhost:$PORT_D/admin?t=$TOK"
    echo "$URL"
    command -v open >/dev/null && open "$URL" || true ;;
  -h|--help|help)
    cat <<'H'
autocut — 터미널에서 쓰는 명령

  autocut            켜고 브라우저 열기
  autocut stop       끄기
  autocut restart    다시 켜기
  autocut status     켜져 있는지 · 버전 · 폴더 확인
  autocut share      무료 공개 주소 만들기 (외부 사람에게 전달, 끝나면 stop)
  autocut open       편집실 열기
  autocut manual     사용법 열기
  autocut dir        설치 폴더 열기
  autocut jobs       최근 작업 폴더 목록
  autocut update     최신 버전으로 올리기
  autocut version    버전 보기
  autocut admin      판매 어드민 열기 (키 발급·결제 요청)
H
    ;;
  *) echo "모르는 명령입니다: $1  ('autocut help' 로 확인)" >&2; exit 1 ;;
esac
