#!/usr/bin/env bash
# apple-notes — Claude Code skill dispatcher for Apple Notes on macOS.
#
# Project structure (enforced by `init`, scanned by all reads):
#   <company_folder>/                ← default: "Firma"
#     <project>/                     ← e.g. ProjektA, Projekt-B
#       inbox/                       ← new, untriaged
#       ready/                       ← triaged, ready-for-work
#       done/                        ← merged / shipped
#       docs/                        ← templates, specs, briefing — NOT issues
#
# Title-prefix convention (recommended, not enforced):
#   BUG:  | FEAT: | IDEA: | FB: | TECH:
#
# Subcommands: init, projects, resolve, notes, get, images, search,
#              create, update, append, delete, move, triage, config.

set -euo pipefail

SKILL_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
HELPER="$SKILL_DIR/scripts/_helper.py"
CONFIG_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/claude/apple-notes"
CACHE_DIR="${XDG_CACHE_HOME:-$HOME/.cache}/claude/apple-notes"
CONFIG_FILE="$CONFIG_DIR/config.json"
MAPPING_FILE="$CONFIG_DIR/mapping.json"

mkdir -p "$CONFIG_DIR" "$CACHE_DIR"
[ -f "$CONFIG_FILE" ] || cat > "$CONFIG_FILE" <<'JSON'
{
  "account": "iCloud",
  "company_folder": "Firma",
  "statuses": ["inbox", "ready", "done", "docs"],
  "default_status": "inbox",
  "default_image_dir": "~/.cache/claude/apple-notes/images"
}
JSON
[ -f "$MAPPING_FILE" ] || echo '{}' > "$MAPPING_FILE"

# Gentle migration: backfill new keys onto pre-existing configs.
python3 - "$CONFIG_FILE" <<'PY'
import json, sys
p = sys.argv[1]
try:
    with open(p) as f:
        c = json.load(f)
except (ValueError, OSError):
    sys.exit(f"Error: config.json unreadable: {p}")
changed = False
for k, v in [
    ("account", "iCloud"),
    ("company_folder", "Firma"),
    ("statuses", ["inbox", "ready", "done", "docs"]),
    ("default_status", "inbox"),
    ("default_image_dir", "~/.cache/claude/apple-notes/images"),
]:
    if k not in c:
        c[k] = v
        changed = True
if changed:
    import os
    with open(p + ".tmp", "w") as f:
        json.dump(c, f, indent=2, ensure_ascii=False)
    os.replace(p + ".tmp", p)
PY

# ─── config readers (single-value via python; lists piped through `tr`) ───
cfg_get() {
  python3 -c '
import json, sys
v=json.load(open(sys.argv[1])).get(sys.argv[2])
if v is None: sys.exit("missing config key: " + sys.argv[2])
if isinstance(v, list): print("\n".join(v))
else: print(v)
' "$CONFIG_FILE" "$1"
}

ACCOUNT="$(cfg_get account)"
COMPANY="$(cfg_get company_folder)"
DEFAULT_STATUS="$(cfg_get default_status)"
DEFAULT_IMG_DIR="$(cfg_get default_image_dir)"
DEFAULT_IMG_DIR="${DEFAULT_IMG_DIR/#\~/$HOME}"   # expand a leading ~
# STATUSES as space-separated list for shell loops
STATUSES="$(cfg_get statuses | tr '\n' ' ')"

die() { echo "Error: $*" >&2; exit 1; }
need() { [ -n "${1:-}" ] || die "missing argument: $2"; }
# Integer flag values are checked here; they are then passed to Python via argv, never spliced into source.
need_int() { case "$1" in ''|*[!0-9]*) die "$2 expects a non-negative integer, got '$1'";; esac; }

# Run AppleScript from stdin with positional args via argv.
osa() { /usr/bin/osascript - "$@"; }
osa_file() { /usr/bin/osascript "$SKILL_DIR/applescripts/$1" "${@:2}"; }

# Validate that a status is in the configured list.
validate_status() {
  local s="$1"
  for known in $STATUSES; do
    [ "$s" = "$known" ] && return 0
  done
  die "unknown status '$s'. Configured: $STATUSES"
}

# ───── templates (heredocs; idempotent on apply) ───────────────────────
template_bug() { cat <<'BODY'
Was funktioniert nicht
<kurz beschreiben, was kaputt ist>

Was hätte passieren sollen
<was wäre die richtige Reaktion gewesen>

Wie kann man es nachstellen
1.
2.
3.

Wann hast du es zuletzt gesehen?

Passiert es immer wieder?  ja / nein / manchmal
BODY
}
template_feat() { cat <<'BODY'
Was soll die App können
<in einem Satz>

Warum brauchst du das
<welches Problem löst es für dich>

Wie könnte das aussehen
<Skizze, Beispiel, oder Screenshot aus einer anderen App>

Woran erkennst du, dass es klappt?
- [ ]
- [ ]
BODY
}
template_idea() { cat <<'BODY'
Deine Idee
<in einem Satz>

Was hat dich darauf gebracht
<Erlebnis, Beobachtung, Gespräch>

Was ist dir noch unklar
-
-
BODY
}
template_fb() { cat <<'BODY'
Was wurde gesagt
<Originalzitat oder kurze Zusammenfassung>

Von wem
<Name, Rolle, oder z. B. „eine Nutzerin">

Stimmung
positiv / neutral / negativ

Was bedeutet das für uns
<deine Einschätzung>
BODY
}
template_tech() { cat <<'BODY'
TECH · area: app | website | infrastruktur · impact: low | medium | high · tags: ...

Was
<Welche technische Schuld / Refactoring>

Warum jetzt
<Wieso ist das wichtig>

Skizze des Ansatzes
<Wie würde man es lösen>
BODY
}
cheatsheet() { cat <<'BODY'
So bringst du Bugs und Feedback ein
───────────────────────────────────

1. Im Ordner „inbox" eine neue Notiz anlegen.

2. Den Titel mit einem dieser Wörter starten (mit Doppelpunkt) —
   das hilft uns beim Sortieren:

   BUG:   wenn etwas nicht funktioniert
   FEAT:  wenn du dir ein neues Feature wünschst
   IDEA:  wenn du eine halb-fertige Idee hast
   FB:    wenn du Feedback weitergeben willst
   (TECH: ist nur für den Entwickler gedacht)

   Wichtig: Halte die erste Zeile (den Titel) kurz — am besten
   ein knapper Satz. Schreibe alle Details darunter in den Text,
   nicht alles in die Titelzeile. Sonst kürzt Apple Notes den
   Titel mit „…" ab und wir müssen länger suchen.

3. Im Ordner „docs" findest du fertige Vorlagen — eine je
   Titel-Typ. So nutzt du sie (funktioniert auf iPhone, iPad,
   Mac und auf iCloud.com unter Windows):

   - die passende Vorlage öffnen (z. B. „VORLAGE BUG")
   - den gesamten Text markieren und kopieren
   - im Ordner „inbox" eine neue, leere Notiz anlegen
   - den Text einfügen
   - den Titel anpassen (aus „VORLAGE BUG" wird z. B.
     „BUG: Login klappt nicht")
   - die Platzhalter im Text ausfüllen

   Tipp für Mac-Nutzer: Vorlage anklicken, dann im Menü
   „Datei" → „Notiz duplizieren" — fertig, dann nur noch in
   den inbox-Ordner ziehen.

4. Screenshots helfen sehr — wie du sie aufnimmst, hängt vom
   Gerät ab:

   - iPhone / iPad: Screenshot wie gewohnt, dann unten links
     auf die Vorschau tippen und „In Notizen sichern" wählen
     (oder das Bild aus der Fotos-App per Teilen-Knopf in die
     Notiz schicken).
   - Windows (iCloud.com im Browser): mit dem Snipping-Tool
     aufnehmen (Windows-Taste + Shift + S), dann in der Notiz
     mit Strg+V einfügen.
   - Mac: Shift+Cmd+4 aufnehmen, dann mit Cmd+V einfügen.

So läuft es weiter:

   inbox    ← hier legst du es ab
   ready    ← der Entwickler hat es gesichtet, wird bald gemacht
   done     ← erledigt

Danke fürs sorgfältige Schreiben!
BODY
}

# ensure_doc_note <project> <title> <body-text>
# Creates the note in <project>/docs only if no note with that name exists there.
ensure_doc_note() {
  local project="$1" title="$2" body="$3"
  local wrapped
  wrapped="$(wrap_plain "$body")"
  osa "$ACCOUNT" "$COMPANY" "$project" "$title" "$wrapped" <<'APPLESCRIPT' >/dev/null
on run argv
  set acct to item 1 of argv
  set parentName to item 2 of argv
  set proj to item 3 of argv
  set t to item 4 of argv
  set b to item 5 of argv
  tell application "Notes"
    set docsFolder to folder "docs" of folder proj of folder parentName of account acct
    set matches to (notes of docsFolder whose name is t)
    if (count of matches) = 0 then
      make new note at docsFolder with properties {body:"<div>" & t & "</div>" & b}
    end if
  end tell
end run
APPLESCRIPT
}

# ───── init ─────────────────────────────────────────────────────────────
cmd_init() {
  if [ "${1:-}" = "--explain" ]; then
    cat <<EOF
Project layout convention
─────────────────────────
  $COMPANY/                       (company folder, in $ACCOUNT)
    <project>/                    one subfolder per app/repo
      inbox/                      new, untriaged
      ready/                      triaged, ready for work
      done/                       merged / shipped
      docs/                       templates + briefing — NOT issues

Title-prefix convention (only requirement for non-technical partners):
  BUG:  | FEAT: | IDEA: | FB: | TECH:

Body: free text. Optional metadata first-line (only TECH template
uses this; the others are deliberately plain for non-technical partners).

Status changes via:  apple-notes move <project> <title> <new-status>
Configured statuses: $STATUSES
EOF
    return 0
  fi
  local project="${1:-}"; need "$project" "<project>"; shift
  local skip_docs=0
  while [ $# -gt 0 ]; do
    case "$1" in
      --no-docs) skip_docs=1; shift ;;
      *) die "unknown flag: $1" ;;
    esac
  done
  local out
  out="$(osa "$ACCOUNT" "$COMPANY" "$project" $STATUSES <<'APPLESCRIPT'
on run argv
  set acct to item 1 of argv
  set parentName to item 2 of argv
  set proj to item 3 of argv
  set wanted to items 4 thru -1 of argv
  set output to ""
  tell application "Notes"
    try
      set parentFolder to folder parentName of account acct
    on error
      return "ERR:company folder missing: " & parentName
    end try
    try
      set projFolder to folder proj of parentFolder
    on error
      return "ERR:project folder missing: " & proj & " (create it in Apple Notes first)"
    end try
    -- Collect existing folder names; tolerate unreadable folders so a
    -- single stale CoreData entry does not block a re-init.
    set existing to {}
    set folderCount to count of folders of projFolder
    repeat with i from 1 to folderCount
      try
        set end of existing to name of folder i of projFolder
      end try
    end repeat
    repeat with s in wanted
      if existing does not contain (s as text) then
        make new folder at projFolder with properties {name:(s as text)}
        set output to output & "folder created: " & s & linefeed
      else
        set output to output & "folder exists:  " & s & linefeed
      end if
    end repeat
  end tell
  return output
end run
APPLESCRIPT
)"
  case "$out" in ERR:*) die "${out#ERR:}";; esac
  printf '%s\n' "$out" | sed '/^$/d'

  if [ "$skip_docs" = "0" ]; then
    echo "seeding templates + cheatsheet in $project/docs/ ..."
    ensure_doc_note "$project" "VORLAGE BUG"   "$(template_bug)"
    ensure_doc_note "$project" "VORLAGE FEAT"  "$(template_feat)"
    ensure_doc_note "$project" "VORLAGE IDEA"  "$(template_idea)"
    ensure_doc_note "$project" "VORLAGE FB"    "$(template_fb)"
    ensure_doc_note "$project" "VORLAGE TECH"  "$(template_tech)"
    ensure_doc_note "$project" "Anleitung: Bugs und Feedback einbringen" "$(cheatsheet)"
    echo "docs seeded (existing notes were not overwritten)"
  fi
}

# ───── projects ─────────────────────────────────────────────────────────
cmd_projects() {
  local json=0
  [ "${1:-}" = "--json" ] && json=1
  local out
  out="$(osa "$ACCOUNT" "$COMPANY" <<'APPLESCRIPT'
on run argv
  set acct to item 1 of argv
  set parentName to item 2 of argv
  set output to ""
  tell application "Notes"
    try
      set parentFolder to folder parentName of account acct
    on error errMsg
      return "ERR:" & errMsg
    end try
    set folderCount to count of folders of parentFolder
    repeat with i from 1 to folderCount
      set sName to ""
      try
        set sf to folder i of parentFolder
        set sName to name of sf
        set totalNotes to (count of notes of sf)
        set subCount to count of folders of sf
        repeat with j from 1 to subCount
          try
            set totalNotes to totalNotes + (count of notes of folder j of sf)
          end try
        end repeat
        set output to output & sName & tab & totalNotes & linefeed
      end try
    end repeat
  end tell
  return output
end run
APPLESCRIPT
)"
  case "$out" in ERR:*) die "${out#ERR:}";; esac
  if [ "$json" = 1 ]; then
    printf '%s' "$out" | python3 -c "
import sys, json
rows=[{'name':n,'notes':int(c)} for n,c in (l.split('\t') for l in sys.stdin if l.strip())]
print(json.dumps(rows, ensure_ascii=False, indent=2))
"
  else
    printf '%s' "$out" | awk -F'\t' 'NF==2 {printf "%-30s %s notes\n", $1, $2}'
  fi
}

# ───── resolve ──────────────────────────────────────────────────────────
cmd_resolve() {
  local repo="${1:-}"
  if [ -z "$repo" ]; then
    repo="$(git -C "$PWD" rev-parse --show-toplevel 2>/dev/null | xargs -I{} basename {} 2>/dev/null || true)"
    [ -z "$repo" ] && repo="$(basename "$PWD")"
  fi
  local key
  key="$(echo "$repo" | tr '[:upper:]' '[:lower:]' | tr -cd 'a-z0-9')"
  [ -n "$key" ] || die "could not derive a project key from '$repo'"

  local cached
  cached="$(python3 -c '
import json, sys
m=json.load(open(sys.argv[1]))
print(m.get(sys.argv[2], ""))
' "$MAPPING_FILE" "$key")"
  if [ -n "$cached" ]; then
    echo "$cached"; return 0
  fi

  local subfolders match
  subfolders="$(cmd_projects | awk '{print $1}')"
  match="$(printf '%s\n' "$subfolders" | python3 -c "
import sys, difflib
key=sys.argv[1]
candidates=[l.strip() for l in sys.stdin if l.strip()]
exact=[c for c in candidates if c.lower()==key]
if exact: print(exact[0]); sys.exit(0)
sub=[c for c in candidates if key in c.lower() or c.lower() in key]
if len(sub)==1: print(sub[0]); sys.exit(0)
if len(sub)>1:
    sys.stderr.write('AMBIGUOUS: '+', '.join(sub)+'\n'); sys.exit(2)
best=difflib.get_close_matches(key,[c.lower() for c in candidates],n=1,cutoff=0.6)
if best:
    for c in candidates:
        if c.lower()==best[0]: print(c); sys.exit(0)
sys.stderr.write('NOMATCH\n'); sys.exit(3)
" "$key")" || {
    local rc=$?
    echo "Available projects:" >&2
    printf '  %s\n' $subfolders >&2
    if [ "$rc" = 2 ]; then
      die "ambiguous match for '$repo'. Set explicitly: apple-notes config set-mapping $key <ProjectName>"
    else
      die "no project matches '$repo'. Set explicitly: apple-notes config set-mapping $key <ProjectName>"
    fi
  }
  python3 -c '
import json, os, sys
path, k, v = sys.argv[1], sys.argv[2], sys.argv[3]
with open(path) as f: m = json.load(f)
m[k] = v
with open(path + ".tmp", "w") as f: json.dump(m, f, indent=2, ensure_ascii=False)
os.replace(path + ".tmp", path)
' "$MAPPING_FILE" "$key" "$match"
  echo "$match"
}

# ─── shared AppleScript helpers: isoDate + squash + folder scanning ────
# scan_notes <project> <status_filter|"">  →  emits tab-separated
#   "<status>\t<title>\t<iso-date>\t<preview400>" rows.
scan_notes() {
  local project="$1"; shift
  local status_filter="${1:-}"
  osa "$ACCOUNT" "$COMPANY" "$project" "$status_filter" <<'APPLESCRIPT'
on run argv
  set acct to item 1 of argv
  set parentName to item 2 of argv
  set proj to item 3 of argv
  set onlyStatus to item 4 of argv
  set output to ""
  tell application "Notes"
    try
      set projFolder to folder proj of folder parentName of account acct
    on error errMsg
      return "ERR:" & errMsg
    end try
    -- Indexed iteration with per-folder try/skip: tolerates unreadable
    -- subfolders (CoreData sync state can leave a folder addressable by
    -- id but unreadable when its notes are fetched).
    set folderCount to count of folders of projFolder
    repeat with i from 1 to folderCount
      set sName to ""
      try
        set sf to folder i of projFolder
        set sName to name of sf
      end try
      if sName is not "" and ((onlyStatus is "") or (onlyStatus is sName)) then
        try
          repeat with n in (notes of sf)
            set modDate to modification date of n
            set p to plaintext of n
            if (count of p) > 400 then set p to (text 1 thru 400 of p)
            set p to my squash(p)
            set output to output & sName & tab & (id of n) & tab & (name of n) & tab & my isoDate(modDate) & tab & p & linefeed
          end repeat
        end try
      end if
    end repeat
  end tell
  return output
end run

on isoDate(d)
  set y to (year of d) as text
  set m to (month of d) as integer
  set dd to (day of d) as integer
  set mPad to text -2 thru -1 of ("0" & m)
  set dPad to text -2 thru -1 of ("0" & dd)
  return y & "-" & mPad & "-" & dPad
end isoDate

on squash(t)
  set text item delimiters of AppleScript to {linefeed, return, tab}
  set parts to text items of t
  set text item delimiters of AppleScript to " "
  set t2 to parts as text
  set text item delimiters of AppleScript to ""
  return t2
end squash
APPLESCRIPT
}

# ───── notes ────────────────────────────────────────────────────────────
cmd_notes() {
  local project="${1:-}"; need "$project" "<project>"; shift
  local status="" preview=80 json=0 limit=0
  while [ $# -gt 0 ]; do
    case "$1" in
      --status) need "${2:-}" --status; status="$2"; shift 2 ;;
      --preview) need_int "${2:-}" --preview; preview="$2"; shift 2 ;;
      --limit) need_int "${2:-}" --limit; limit="$2"; shift 2 ;;
      --json) json=1; shift ;;
      *) die "unknown flag: $1" ;;
    esac
  done
  local out
  out="$(scan_notes "$project" "$status")"
  case "$out" in ERR:*) die "${out#ERR:}";; esac

  printf '%s' "$out" | python3 -c "
import sys, json
rows=[]
preview=int(sys.argv[1])
for line in sys.stdin:
    line=line.rstrip('\n')
    if not line: continue
    parts=line.split('\t', 4)
    if len(parts)<5: continue
    st, nid, title, date, body = parts
    rows.append({'status':st,'id':nid,'title':title,'modified':date,'preview':body[:preview]})

rows.sort(key=lambda r:(r['status'], r['modified']), reverse=True)
limit=int(sys.argv[2])
if limit>0: rows=rows[:limit]

if sys.argv[3] == '1':
    print(json.dumps(rows, ensure_ascii=False, indent=2))
else:
    current=None
    for r in rows:
        if r['status']!=current:
            current=r['status']
            print(f\"\\n[{current}]\")
        print(f\"  {r['modified']}  {r['title'][:50]:<50}  {r['preview']}\")
" "$preview" "$limit" "$json"
}

# ─── note_index <project> ─────────────────────────────────────────────────
# Dumps every note in the project as "<status>\t<id>\t<name>" rows. The id is
# the stable x-coredata handle; the name is squashed (no tabs/newlines) and may
# be a truncated first line ending in an ellipsis — that is fine, find_note
# below tolerates it. ERR: prefix on failure.
note_index() {
  local project="$1"
  osa "$ACCOUNT" "$COMPANY" "$project" <<'APPLESCRIPT'
on run argv
  set acct to item 1 of argv
  set parentName to item 2 of argv
  set proj to item 3 of argv
  set output to ""
  tell application "Notes"
    try
      set projFolder to folder proj of folder parentName of account acct
    on error errMsg
      return "ERR:" & errMsg
    end try
    set folderCount to count of folders of projFolder
    repeat with i from 1 to folderCount
      set sName to ""
      try
        set sf to folder i of projFolder
        set sName to name of sf
      end try
      if sName is not "" then
        try
          repeat with n in (notes of sf)
            set output to output & sName & tab & (id of n) & tab & my squash(name of n) & linefeed
          end repeat
        end try
      end if
    end repeat
  end tell
  return output
end run

on squash(t)
  set text item delimiters of AppleScript to {linefeed, return, tab}
  set parts to text items of t
  set text item delimiters of AppleScript to " "
  set t2 to parts as text
  set text item delimiters of AppleScript to ""
  return t2
end squash
APPLESCRIPT
}

# ─── find_note <project> <title-or-id> ────────────────────────────────────
# Tolerant resolver. Sets globals FN_STATUS / FN_ID / FN_NAME on success, or
# `die`s on not-found / ambiguous / AppleScript error. Accepts a raw
# x-coredata:// id (matched exactly) or a title that may be truncated, cut to
# a different length, or use "..." instead of "…" — see _helper.py match-title.
FN_STATUS=""; FN_ID=""; FN_NAME=""
find_note() {
  local project="$1" title="$2"
  local idx
  idx="$(note_index "$project")"
  case "$idx" in ERR:*) die "${idx#ERR:}";; esac
  local res
  res="$(printf '%s' "$idx" | python3 "$HELPER" match-title "$title")"
  case "$res" in
    OK*)
      FN_STATUS="$(printf '%s' "$res" | cut -f2)"
      FN_ID="$(printf '%s' "$res" | cut -f3)"
      FN_NAME="$(printf '%s' "$res" | cut -f4-)"
      ;;
    AMBIG*)
      local cands; cands="$(printf '%s' "$res" | cut -f2-)"
      die "ambiguous title in $project — matches: $cands. Disambiguate with the note id from 'notes --json' (pass it as <title>)."
      ;;
    *)
      die "note not found in any subfolder of $project: $title"
      ;;
  esac
}

# ─── body_by_id <id> ──────────────────────────────────────────────────────
# Returns the raw HTML body of a note addressed by its stable id.
body_by_id() {
  osa "$1" <<'APPLESCRIPT'
on run argv
  tell application "Notes" to return body of (note id (item 1 of argv))
end run
APPLESCRIPT
}

# ───── get ──────────────────────────────────────────────────────────────
cmd_get() {
  local project="${1:-}"; need "$project" "<project>"
  local title="${2:-}"; need "$title" "<title>"
  shift 2
  local format=text
  while [ $# -gt 0 ]; do
    case "$1" in
      --format) need "${2:-}" --format; format="$2"; shift 2 ;;
      *) die "unknown flag: $1" ;;
    esac
  done
  find_note "$project" "$title"

  local out
  out="$(body_by_id "$FN_ID")"
  case "$out" in ERR:*) die "${out#ERR:}";; esac
  case "$format" in
    text) printf '%s' "$out" | python3 "$HELPER" to-text ;;
    html) printf '%s' "$out" | python3 "$HELPER" strip-base64 ;;
    raw)  printf '%s\n' "$out" ;;
    *) die "unknown --format: $format (use text|html|raw)" ;;
  esac
}

# ───── images ───────────────────────────────────────────────────────────
cmd_images() {
  local project="${1:-}"; need "$project" "<project>"
  local title="${2:-}"; need "$title" "<title>"
  shift 2
  local out_dir="$DEFAULT_IMG_DIR"
  while [ $# -gt 0 ]; do
    case "$1" in
      --out) need "${2:-}" --out; out_dir="$2"; shift 2 ;;
      *) die "unknown flag: $1" ;;
    esac
  done
  find_note "$project" "$title"

  local slug
  slug="$(echo "${project}_${FN_NAME}" | tr '[:upper:]' '[:lower:]' | tr -cs 'a-z0-9' '-' | sed 's/^-//;s/-$//' | cut -c1-60)"
  local target="$out_dir/$slug"
  umask 077                             # extracted images are private: dirs 0700, files 0600
  mkdir -p "$target"

  local body
  body="$(body_by_id "$FN_ID")"
  case "$body" in ERR:*) die "${body#ERR:}";; esac
  printf '%s' "$body" | python3 "$HELPER" extract-images "$target"
}

# ───── search ───────────────────────────────────────────────────────────
cmd_search() {
  local query="${1:-}"; need "$query" "<query>"; shift
  local project="" json=0 preview=80
  while [ $# -gt 0 ]; do
    case "$1" in
      --project) need "${2:-}" --project; project="$2"; shift 2 ;;
      --json) json=1; shift ;;
      --preview) need_int "${2:-}" --preview; preview="$2"; shift 2 ;;
      *) die "unknown flag: $1" ;;
    esac
  done

  local out
  out="$(osa "$ACCOUNT" "$COMPANY" "$query" "$project" <<'APPLESCRIPT'
on run argv
  set acct to item 1 of argv
  set parentName to item 2 of argv
  set q to item 3 of argv
  set onlyProject to item 4 of argv
  set output to ""
  tell application "Notes"
    try
      set parentFolder to folder parentName of account acct
    on error errMsg
      return "ERR:" & errMsg
    end try
    if onlyProject is "" then
      set projs to folders of parentFolder
    else
      set projs to {folder onlyProject of parentFolder}
    end if
    repeat with proj in projs
      set pName to name of proj
      set folderCount to count of folders of proj
      repeat with i from 1 to folderCount
        set sName to ""
        try
          set sf to folder i of proj
          set sName to name of sf
        end try
        if sName is not "" then
          try
            set hits to (notes of sf whose name contains q or plaintext contains q)
            repeat with n in hits
              set modDate to modification date of n
              set p to plaintext of n
              if (count of p) > 400 then set p to (text 1 thru 400 of p)
              set p to my squash(p)
              set output to output & pName & tab & sName & tab & (id of n) & tab & (name of n) & tab & my isoDate(modDate) & tab & p & linefeed
            end repeat
          end try
        end if
      end repeat
    end repeat
  end tell
  return output
end run

on isoDate(d)
  set y to (year of d) as text
  set m to (month of d) as integer
  set dd to (day of d) as integer
  set mPad to text -2 thru -1 of ("0" & m)
  set dPad to text -2 thru -1 of ("0" & dd)
  return y & "-" & mPad & "-" & dPad
end isoDate

on squash(t)
  set text item delimiters of AppleScript to {linefeed, return, tab}
  set parts to text items of t
  set text item delimiters of AppleScript to " "
  set t2 to parts as text
  set text item delimiters of AppleScript to ""
  return t2
end squash
APPLESCRIPT
)"
  case "$out" in ERR:*) die "${out#ERR:}";; esac

  printf '%s' "$out" | python3 -c "
import sys, json
rows=[]
preview=int(sys.argv[1])
for line in sys.stdin:
    line=line.rstrip('\n')
    if not line: continue
    parts=line.split('\t', 5)
    if len(parts)<6: continue
    proj, st, nid, title, date, body = parts
    rows.append({'project':proj,'status':st,'id':nid,'title':title,'modified':date,'preview':body[:preview]})
rows.sort(key=lambda r:r['modified'], reverse=True)

if sys.argv[2] == '1':
    print(json.dumps(rows, ensure_ascii=False, indent=2))
else:
    for r in rows:
        print(f\"{r['modified']}  {r['project'][:12]:<12}  {r['status'][:10]:<10}  {r['title'][:40]:<40}  {r['preview']}\")
" "$preview" "$json"
}

# ───── create / update / append ─────────────────────────────────────────
read_body() {
  local body_file=""
  while [ $# -gt 0 ]; do
    case "$1" in
      --body-file) need "${2:-}" --body-file; body_file="$2"; shift 2 ;;
      *) shift ;;
    esac
  done
  if [ -n "$body_file" ]; then
    cat "$body_file"
  elif [ -t 0 ]; then
    die "no body provided. Pipe content via stdin or use --body-file"
  else
    cat
  fi
}

wrap_plain() {
  printf '%s' "$1" | python3 -c "
import sys, html
lines=sys.stdin.read().splitlines() or ['']
out=[]
for l in lines:
    out.append('<div>'+html.escape(l)+'</div>' if l else '<div><br></div>')
print(''.join(out))
"
}

cmd_create() {
  local project="${1:-}"; need "$project" "<project>"
  local title="${2:-}"; need "$title" "<title>"
  shift 2
  local status="$DEFAULT_STATUS"
  local body_args=()
  while [ $# -gt 0 ]; do
    case "$1" in
      --status) need "${2:-}" --status; status="$2"; shift 2 ;;
      --body-file) need "${2:-}" --body-file; body_args+=("--body-file" "$2"); shift 2 ;;
      *) die "unknown flag: $1" ;;
    esac
  done
  validate_status "$status"
  local body
  body="$(read_body "${body_args[@]+"${body_args[@]}"}")"
  if ! printf '%s' "$body" | grep -q '<'; then
    body="$(wrap_plain "$body")"
  fi
  local out
  out="$(osa_file create_note.applescript "$ACCOUNT" "$COMPANY" "$project" "$status" "$title" "$body")"
  case "$out" in ERR:*) die "${out#ERR:}";; esac
  echo "created: $title in $project/$status"
}

cmd_update() {
  local project="${1:-}"; need "$project" "<project>"
  local title="${2:-}"; need "$title" "<title>"
  shift 2
  local body
  body="$(read_body "$@")"
  if ! printf '%s' "$body" | grep -q '<'; then
    body="$(wrap_plain "$body")"
  fi
  find_note "$project" "$title"

  local out
  out="$(osa "$FN_ID" "$FN_NAME" "$body" <<'APPLESCRIPT'
on run argv
  set theId to item 1 of argv
  set t to item 2 of argv
  set b to item 3 of argv
  tell application "Notes"
    set body of (note id theId) to "<div>" & t & "</div>" & b
  end tell
  return "OK"
end run
APPLESCRIPT
)"
  case "$out" in ERR:*) die "${out#ERR:}";; esac
  echo "updated: $FN_NAME in $project/$FN_STATUS"
}

cmd_append() {
  local project="${1:-}"; need "$project" "<project>"
  local title="${2:-}"; need "$title" "<title>"
  shift 2
  local body
  body="$(read_body "$@")"
  if ! printf '%s' "$body" | grep -q '<'; then
    body="$(wrap_plain "$body")"
  fi
  find_note "$project" "$title"

  local out
  out="$(osa "$FN_ID" "$body" <<'APPLESCRIPT'
on run argv
  set theId to item 1 of argv
  set b to item 2 of argv
  tell application "Notes"
    set theNote to note id theId
    set body of theNote to (body of theNote) & b
  end tell
  return "OK"
end run
APPLESCRIPT
)"
  case "$out" in ERR:*) die "${out#ERR:}";; esac
  echo "appended to: $FN_NAME in $project/$FN_STATUS"
}

# ───── triage ───────────────────────────────────────────────────────────
# Lists inbox notes with health score: title prefix only.
# (Body metadata first-line is intentionally not scored — ProjektA-templates
# are plain free-form text and would otherwise be flagged as warn.)
cmd_triage() {
  local project="${1:-}"; need "$project" "<project>"; shift
  local json=0
  while [ $# -gt 0 ]; do
    case "$1" in
      --json) json=1; shift ;;
      *) die "unknown flag: $1" ;;
    esac
  done
  local out
  out="$(osa "$ACCOUNT" "$COMPANY" "$project" <<'APPLESCRIPT'
on run argv
  set acct to item 1 of argv
  set parentName to item 2 of argv
  set proj to item 3 of argv
  set output to ""
  tell application "Notes"
    try
      set inboxFolder to folder "inbox" of folder proj of folder parentName of account acct
    on error
      return "ERR:inbox folder missing — run: apple-notes init " & proj
    end try
    repeat with n in (notes of inboxFolder)
      set nName to name of n
      set p to plaintext of n
      -- First non-empty paragraph of plaintext, excluding the title line.
      set firstMeta to ""
      set pars to paragraphs of p
      set seenTitle to false
      repeat with par in pars
        set parText to par as text
        if parText is not "" then
          if seenTitle is false then
            set seenTitle to true
          else
            set firstMeta to parText
            exit repeat
          end if
        end if
      end repeat
      if (count of firstMeta) > 200 then set firstMeta to (text 1 thru 200 of firstMeta)
      set output to output & nName & tab & firstMeta & linefeed
    end repeat
  end tell
  return output
end run
APPLESCRIPT
)"
  case "$out" in ERR:*) die "${out#ERR:}";; esac

  printf '%s' "$out" | python3 -c "
import sys, json, re
PREFIX_RE = re.compile(r'^(BUG|FEAT|IDEA|FB|TECH):\s+\S')
rows=[]
for line in sys.stdin:
    line=line.rstrip('\n')
    if not line: continue
    parts=line.split('\t', 1)
    if len(parts)<2: parts.append('')
    title, meta = parts
    issues=[]
    if not PREFIX_RE.match(title):
        issues.append('missing-prefix')
    score='ok' if not issues else 'warn'
    rows.append({'title':title,'meta':meta,'score':score,'issues':issues})

ok=sum(1 for r in rows if r['score']=='ok')
warn=sum(1 for r in rows if r['score']=='warn')

if $json:
    print(json.dumps({'total':len(rows),'ok':ok,'warn':warn,'notes':rows}, ensure_ascii=False, indent=2))
else:
    sym={'ok':'✓','warn':'⚠'}
    for r in rows:
        tag = (', '.join(r['issues']) or 'looks good')
        print(f\"  {sym[r['score']]} {r['title'][:55]:<55} {tag}\")
    print(f\"\\nsummary: {len(rows)} notes — {ok} ok, {warn} warn\")
"
}

# ───── delete / move ────────────────────────────────────────────────────
cmd_delete() {
  local project="${1:-}"; need "$project" "<project>"
  local title="${2:-}"; need "$title" "<title>"
  shift 2
  local force=0
  [ "${1:-}" = "--force" ] && force=1
  if [ "$force" = 0 ]; then
    echo "About to delete '$title' in '$project'. Re-run with --force to confirm." >&2
    exit 1
  fi
  find_note "$project" "$title"

  local out
  out="$(osa "$FN_ID" <<'APPLESCRIPT'
on run argv
  tell application "Notes" to delete (note id (item 1 of argv))
  return "OK"
end run
APPLESCRIPT
)"
  case "$out" in ERR:*) die "${out#ERR:}";; esac
  echo "deleted: $FN_NAME from $project/$FN_STATUS (moved to Recently Deleted)"
}

# move <project> <title> <new-status>  →  changes status within same project
cmd_move() {
  local project="${1:-}"; need "$project" "<project>"
  local title="${2:-}"; need "$title" "<title>"
  local new_status="${3:-}"; need "$new_status" "<new-status>"
  validate_status "$new_status"
  find_note "$project" "$title"
  if [ "$FN_STATUS" = "$new_status" ]; then
    echo "already in $new_status: $FN_NAME"
    return 0
  fi

  local out
  out="$(osa "$ACCOUNT" "$COMPANY" "$project" "$new_status" "$FN_ID" <<'APPLESCRIPT'
on run argv
  set acct to item 1 of argv
  set parentName to item 2 of argv
  set proj to item 3 of argv
  set toStatus to item 4 of argv
  set theId to item 5 of argv
  tell application "Notes"
    set projFolder to folder proj of folder parentName of account acct
    try
      set toFolder to folder toStatus of projFolder
    on error
      return "ERR:target status folder missing: " & toStatus & " (run: apple-notes init " & proj & ")"
    end try
    move (note id theId) to toFolder
  end tell
  return "OK"
end run
APPLESCRIPT
)"
  case "$out" in ERR:*) die "${out#ERR:}";; esac
  echo "moved: $FN_NAME from $project/$FN_STATUS to $project/$new_status"
}

# ───── config ───────────────────────────────────────────────────────────
cmd_config() {
  local sub="${1:-}"
  case "$sub" in
    show)
      echo "config:  $CONFIG_FILE"
      cat "$CONFIG_FILE"
      echo ""
      echo "mapping: $MAPPING_FILE"
      cat "$MAPPING_FILE"
      ;;
    set-mapping)
      local key="${2:-}"; need "$key" "<repo-key>"
      local val="${3:-}"; need "$val" "<project-name>"
      key="$(echo "$key" | tr '[:upper:]' '[:lower:]' | tr -cd 'a-z0-9')"
      python3 - "$MAPPING_FILE" "$key" "$val" <<'PY'
import json, os, sys
path, k, v = sys.argv[1], sys.argv[2], sys.argv[3]
with open(path) as f: m = json.load(f)
m[k] = v
with open(path + ".tmp", "w") as f: json.dump(m, f, indent=2, ensure_ascii=False)
os.replace(path + ".tmp", path)
print(f"mapped {k!r} -> {v!r}")
PY
      ;;
    set)
      local key="${2:-}"; need "$key" "<key>"
      local val="${3:-}"; need "$val" "<value>"
      python3 - "$CONFIG_FILE" "$key" "$val" <<'PY'
import json, os, sys
path, k, v = sys.argv[1], sys.argv[2], sys.argv[3]
with open(path) as f: c = json.load(f)
c[k] = v
with open(path + ".tmp", "w") as f: json.dump(c, f, indent=2, ensure_ascii=False)
os.replace(path + ".tmp", path)
print(f"set {k!r} = {v!r}")
PY
      ;;
    *) die "config subcommands: show | set <key> <value> | set-mapping <repo> <project>" ;;
  esac
}

# ───── usage ────────────────────────────────────────────────────────────
usage() {
  cat <<EOF
apple-notes — Apple Notes access for Claude Code

Status folders (per project, configurable): $STATUSES
Default status for create: $DEFAULT_STATUS

Usage:
  apple-notes init <PROJECT> [--no-docs]                create folders + seed templates
  apple-notes init --explain                            print convention doc
  apple-notes projects [--json]
  apple-notes resolve [REPO]
  apple-notes notes <PROJECT> [--status S] [--preview N] [--limit N] [--json]
  apple-notes get <PROJECT> <TITLE> [--format text|html|raw]
  apple-notes images <PROJECT> <TITLE> [--out DIR]
  apple-notes search <QUERY> [--project NAME] [--json] [--preview N]
  apple-notes create <PROJECT> <TITLE> [--status S] [--body-file F]  (body on stdin)
  apple-notes update <PROJECT> <TITLE> [--body-file F]               (body on stdin)
  apple-notes append <PROJECT> <TITLE> [--body-file F]               (body on stdin)
  apple-notes delete <PROJECT> <TITLE> --force
  apple-notes move <PROJECT> <TITLE> <NEW_STATUS>
  apple-notes triage <PROJECT> [--json]                 inbox health check
  apple-notes config show
  apple-notes config set <key> <value>
  apple-notes config set-mapping <repo-key> <project-name>

Config:  $CONFIG_FILE
Mapping: $MAPPING_FILE
EOF
}

# ───── dispatcher ───────────────────────────────────────────────────────
cmd="${1:-}"
shift || true
case "$cmd" in
  init)     cmd_init "$@" ;;
  projects) cmd_projects "$@" ;;
  resolve)  cmd_resolve "$@" ;;
  notes)    cmd_notes "$@" ;;
  get)      cmd_get "$@" ;;
  images)   cmd_images "$@" ;;
  search)   cmd_search "$@" ;;
  create)   cmd_create "$@" ;;
  update)   cmd_update "$@" ;;
  append)   cmd_append "$@" ;;
  delete)   cmd_delete "$@" ;;
  move)     cmd_move "$@" ;;
  triage)   cmd_triage "$@" ;;
  config)   cmd_config "$@" ;;
  -h|--help|help|"") usage ;;
  *) usage; die "unknown command: $cmd" ;;
esac
