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

echo "▶️  STARTING send_to_notion_image.sh"

# Load local env file if present (do not commit)
ENV_FILE="$HOME/.config/sendpreview-2-notion/.env"
if [[ -f "$ENV_FILE" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$ENV_FILE"
  set +a
fi

echo "▶️  READ env file"

die() { echo "❌ $*" >&2; exit 1; }

usage() {
  cat <<'EOF'
Usage: send_to_notion_image.sh [--dry-run] [--check-deps] /path/to/image1 [image2 ...]

Options:
  --dry-run     Validate inputs and show the Notion requests that would be made.
                Does not prompt via GUI, require Notion credentials, or call Notion.
  --check-deps  Verify local command dependencies and exit.

Environment:
  SENDPREVIEW_DRY_RUN=1      Same as --dry-run.
  SENDPREVIEW_TITLE="Title"   Use this title instead of prompting; useful for tests.
EOF
}

DRY_RUN="${SENDPREVIEW_DRY_RUN:-0}"
CHECK_DEPS=0

while [[ $# -gt 0 ]]; do
  case "$1" in
    --dry-run)
      DRY_RUN=1
      shift
      ;;
    --check-deps)
      CHECK_DEPS=1
      shift
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    --)
      shift
      break
      ;;
    -*)
      usage >&2
      die "Unknown option: $1"
      ;;
    *)
      break
      ;;
  esac
done

[[ "$CHECK_DEPS" == "1" || $# -ge 1 ]] || { usage >&2; exit 1; }

# --- CONFIG ---
if [[ "$DRY_RUN" != "1" && "$CHECK_DEPS" != "1" ]]; then
  : "${NOTION_TOKEN:?Set NOTION_TOKEN (Notion internal integration token)}"
  : "${NOTES_DB_ID:?Set NOTES_DB_ID (target Notion database id)}"
fi

PROP_TITLE="${PROP_TITLE:-Name}"
PROP_TYPE="${PROP_TYPE:-Type}"
TYPE_VALUE="${TYPE_VALUE:-Image}"
NOTION_VERSION="${NOTION_VERSION:-2025-09-03}"
NOTES_DB_ID="${NOTES_DB_ID:-DRY_RUN_DATABASE_ID}"
AUTH_HEADER="Authorization: Bearer ${NOTION_TOKEN:-DRY_RUN_NOTION_TOKEN}"

command -v curl >/dev/null || die "curl not found"
command -v jq >/dev/null || die "jq not found. Install: brew install jq"
if [[ "$DRY_RUN" != "1" && -z "${SENDPREVIEW_TITLE:-}" ]]; then
  command -v osascript >/dev/null || die "osascript not found; this script must run on macOS"
fi

if [[ "$CHECK_DEPS" == "1" ]]; then
  echo "✅ Dependencies available"
  exit 0
fi

infer_mime_from_ext() {
  local fn="$1" ext="${fn##*.}"
  ext="$(printf '%s' "$ext" | tr '[:upper:]' '[:lower:]')"
  case "$ext" in
    jpg|jpeg) echo "image/jpeg" ;;
    png)      echo "image/png" ;;
    heic)     echo "image/heic" ;;
    gif)      echo "image/gif" ;;
    webp)     echo "image/webp" ;;
    tif|tiff) echo "image/tiff" ;;
    bmp)      echo "image/bmp" ;;
    *)        echo "application/octet-stream" ;;
  esac
}

for img in "$@"; do
  [[ -f "$img" ]] || die "Not a file: $img"

  filename="$(basename "$img")"
  default_title="${filename%.*}"

  echo "🖼️  File: $filename"
  if [[ "$DRY_RUN" == "1" ]]; then
    page_title="${SENDPREVIEW_TITLE:-$default_title}"
    echo "🧪 Dry run: using title \"$page_title\""
  elif [[ -n "${SENDPREVIEW_TITLE:-}" ]]; then
    page_title="$SENDPREVIEW_TITLE"
    echo "📝 Using title from SENDPREVIEW_TITLE"
  else
    echo "📝 Prompting for title…"
    page_title="$(osascript - "$default_title" <<'APPLESCRIPT'
on run argv
  set defaultTitle to item 1 of argv
  tell application "System Events"
    activate
    try
      set d to display dialog "Notion page title:" default answer defaultTitle with title "Send Image to Notion" buttons {"Cancel","OK"} default button "OK"
      return text returned of d
    on error number -128
      return ""
    end try
  end tell
end run
APPLESCRIPT
)"
  fi

  [[ -n "$page_title" ]] || { echo "Cancelled for: $filename"; continue; }

  mime="$(/usr/bin/file -b --mime-type "$img" 2>/dev/null || true)"
  if [[ -z "$mime" || "$mime" == *"cannot open"* ]]; then
    mime="$(infer_mime_from_ext "$filename")"
  fi
  echo "📦 MIME: $mime"

  create_upload_payload="$(jq -n --arg fn "$filename" --arg ct "$mime" '{mode:"single_part", filename:$fn, content_type:$ct}')"
  create_page_payload="$(jq -n \
    --arg db "$NOTES_DB_ID" \
    --arg titleProp "$PROP_TITLE" \
    --arg typeProp "$PROP_TYPE" \
    --arg title "$page_title" \
    --arg typeVal "$TYPE_VALUE" \
    '{
      parent: { database_id: $db },
      properties: {
        ($titleProp): { title: [ { text: { content: $title } } ] },
        ($typeProp): { select: { name: $typeVal } }
      }
    }')"

  if [[ "$DRY_RUN" == "1" ]]; then
    echo "🧪 Dry run: would POST https://api.notion.com/v1/file_uploads"
    echo "$create_upload_payload"
    echo "🧪 Dry run: would upload file bytes for $filename"
    echo "🧪 Dry run: would POST https://api.notion.com/v1/pages"
    echo "$create_page_payload"
    echo "🧪 Dry run: would PATCH https://api.notion.com/v1/blocks/DRY_RUN_PAGE_ID/children"
    echo "✅ Dry run passed: $filename → \"$page_title\""
    continue
  fi

  upload_obj="$(
    curl -sS --fail-with-body --request POST \
      --url "https://api.notion.com/v1/file_uploads" \
      -H "$AUTH_HEADER" \
      -H "Content-Type: application/json" \
      -H "Notion-Version: $NOTION_VERSION" \
      --data "$create_upload_payload"
  )"

  upload_id="$(echo "$upload_obj" | jq -r '.id')"
  upload_url="$(echo "$upload_obj" | jq -r '.upload_url')"
  [[ "$upload_id" != "null" && -n "$upload_id" ]] || die "Failed to create upload object: $upload_obj"
  [[ "$upload_url" != "null" && -n "$upload_url" ]] || die "Missing upload_url: $upload_obj"

  curl -sS --fail-with-body --request POST \
    --url "$upload_url" \
    -H "$AUTH_HEADER" \
    -H "Notion-Version: $NOTION_VERSION" \
    -F "file=@${img}" >/dev/null

  page_resp="$(
    curl -sS --fail-with-body --request POST \
      --url "https://api.notion.com/v1/pages" \
      -H "$AUTH_HEADER" \
      -H "Content-Type: application/json" \
      -H "Notion-Version: $NOTION_VERSION" \
      --data "$create_page_payload"
  )"

  page_id="$(echo "$page_resp" | jq -r '.id')"
  [[ "$page_id" != "null" && -n "$page_id" ]] || die "Failed to create page: $page_resp"

  curl -sS --fail-with-body --request PATCH \
    --url "https://api.notion.com/v1/blocks/${page_id}/children" \
    -H "$AUTH_HEADER" \
    -H "Content-Type: application/json" \
    -H "Notion-Version: $NOTION_VERSION" \
    --data "$(jq -n --arg upid "$upload_id" '{
      children: [
        { type: "image",
          image: { caption: [], type: "file_upload", file_upload: { id: $upid } }
        }
      ]
    }')" >/dev/null

  echo "✅ Sent: $filename → \"$page_title\""
done
