#!/usr/bin/osascript -l JavaScript

// Yap Dictation for Alfred: reads the history Yap keeps on this Mac and answers Alfred.
//
//   ./yap-history search "words"   Script Filter items: dictations whose text holds every word, newest first
//   ./yap-history last              Script Filter item: the newest dictation
//   ./yap-history text              the newest dictation's text alone (for the Paste Last Dictation Hotkey)
//
// Yap writes one SQLite file per edition: the direct download and the Setapp edition in Application Support, the
// Mac App Store edition inside its sandbox container. This script only reads them, with the sqlite3 that ships
// with macOS, and sends nothing anywhere.

ObjC.import("Foundation")

const GET_YAP_URL = "https://yapapp.cc/mac?utm_source=alfred&utm_medium=workflow&utm_campaign=alfred-gallery"
const SEARCH_LIMIT = 200
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]

function envVar(name) {
  const value = $.NSProcessInfo.processInfo.environment.objectForKey(name)
  return value.isNil() ? "" : value.js
}

function historyFiles() {
  const home = envVar("HOME")
  const files = [
    `${home}/Library/Application Support/Yap/dictation-history/history.sqlite`,
    `${home}/Library/Containers/cc.yapapp.mac/Data/Library/Application Support/Yap/dictation-history/history.sqlite`,
  ]
  return files.filter(file => $.NSFileManager.defaultManager.fileExistsAtPath(file))
}

function shellQuote(text) {
  return `'${text.replace(/'/g, `'\\''`)}'`
}

// A word as a LIKE pattern: SQL quotes doubled, and % _ \ taken literally.
function likePattern(word) {
  return `'%${word.replace(/[\\%_]/g, char => `\\${char}`).replace(/'/g, "''")}%'`
}

// Dictations with text, newest first, from every Yap edition on this Mac.
function readDictations(words, limit) {
  const app = Application.currentApplication()
  app.includeStandardAdditions = true
  const filters = words.map(word => ` AND text LIKE ${likePattern(word)} ESCAPE '\\'`).join("")
  const sql = `SELECT id, text, created_at, status, word_count FROM dictations WHERE length(trim(text)) > 0${filters} ORDER BY created_at DESC LIMIT ${limit}`
  let rows = []
  for (const file of historyFiles()) {
    let output = ""
    try { output = app.doShellScript(`/usr/bin/sqlite3 -json ${shellQuote(file)} ${shellQuote(sql)}`) } catch (error) { continue }
    if (output.trim()) rows = rows.concat(JSON.parse(output))
  }
  return rows.sort((a, b) => b.created_at - a.created_at).slice(0, limit)
}

// What Yap did with a dictation it did not type into an app itself; nothing when it did.
function statusLabel(status) {
  if (status === "inserted" || status === "sent" || status === "copied") return ""
  if (status === "kept") return "Kept"
  if (status === "saved") return "Saved"
  if (status === "focus-changed") return "Not typed: focus changed"
  return "Not typed"
}

function when(milliseconds) {
  const date = new Date(milliseconds)
  const now = new Date()
  const time = `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`
  const day = `${MONTHS[date.getMonth()]} ${date.getDate()}`
  if (date.toDateString() === now.toDateString()) return `Today ${time}`
  return date.getFullYear() === now.getFullYear() ? `${day}, ${time}` : `${day} ${date.getFullYear()}, ${time}`
}

function item(row) {
  const words = `${row.word_count} ${row.word_count === 1 ? "word" : "words"}`
  const label = statusLabel(row.status)
  return {
    title: row.text.replace(/\s+/g, " ").trim(),
    subtitle: [when(row.created_at), words, label].filter(Boolean).join(" · "),
    arg: row.text,
    text: { copy: row.text, largetype: row.text },
    mods: { cmd: { arg: row.text, subtitle: "Copy to the clipboard without pasting" } },
  }
}

function getYapItem(title) {
  return {
    title,
    subtitle: "Press ↩ to get Yap, the offline dictation app for Mac",
    arg: GET_YAP_URL,
    variables: { get_yap: "1" },
    mods: { cmd: { valid: false, subtitle: "Yap is needed for this workflow" } },
  }
}

function run(argv) {
  const mode = argv[0] || "search"
  const query = (argv[1] || "").trim()
  const hasYap = historyFiles().length > 0

  if (mode === "text") {
    const [newest] = hasYap ? readDictations([], 1) : []
    return newest ? newest.text : ""
  }

  if (mode === "last") {
    const [newest] = hasYap ? readDictations([], 1) : []
    return JSON.stringify({ items: [newest ? item(newest) : getYapItem("Yap has no dictations on this Mac yet")] })
  }

  if (!hasYap) return JSON.stringify({ items: [getYapItem("Yap is not on this Mac yet")] })
  const words = query.split(/\s+/).filter(Boolean)
  const rows = readDictations(words, SEARCH_LIMIT)
  if (rows.length) return JSON.stringify({ items: rows.map(item) })
  const empty = words.length
    ? { title: "No dictation holds those words", subtitle: "Try fewer or other words", valid: false }
    : getYapItem("Yap has no dictations on this Mac yet")
  return JSON.stringify({ items: [empty] })
}
