(ns wordfreq (:export [main]))

(defn- letter? [c :i64] :bool
  (and (>= c 97) (<= c 122)))

(defn- word-end [text :string start :i64] :i64
  (let [n (string-byte-length text)]
    (loop [i start]
      (if (< i n)
        (if (letter? (string-code-point-at text i))
          (recur (+ i 1))
          i)
        i))))

(defn- word-starts [text :string] :vector-i64
  (let [n (string-byte-length text)]
    (loop [i 0 starts []]
      (if (>= i n)
        starts
        (if (letter? (string-code-point-at text i))
          (recur (word-end text i) (vector-conj starts i))
          (recur (+ i 1) starts))))))

(defn- word-at [text :string start :i64] :string
  (string-substring text start (word-end text start)))

;; Count each distinct word at its first occurrence. Later copies score zero.
(defn- frequency [text :string starts :vector-i64 index :i64] :i64
  (let [word (word-at text (vector-at starts index))
        n (vector-count starts)]
    (loop [i 0 count 0]
      (if (= i n)
        count
        (if (string=? word (word-at text (vector-at starts i)))
          (if (< i index)
            0
            (recur (+ i 1) (+ count 1)))
          (recur (+ i 1) count))))))

(defn- word-counts [text :string starts :vector-i64] :vector-i64
  (let [n (vector-count starts)]
    (loop [i 0 counts []]
      (if (= i n)
        counts
        (recur (+ i 1) (vector-conj counts (frequency text starts i)))))))

;; Select the next positive count, with first occurrence breaking ties.
(defn- next-index [counts :vector-i64 before-count :i64 before-index :i64] :i64
  (let [n (vector-count counts)]
    (loop [i 0 best-index -1 best-count 0]
      (if (= i n)
        best-index
        (let [count (vector-at counts i)]
          (if (and (> count best-count)
                   (or (< count before-count)
                       (and (= count before-count) (> i before-index))))
            (recur (+ i 1) i count)
            (recur (+ i 1) best-index best-count)))))))

(defn- top-n [text :string limit :i64 starts :vector-i64] :i64
  (let [counts (word-counts text starts)]
    (loop [left limit before-count (+ (vector-count starts) 1) before-index -1]
      (if (<= left 0)
        0
        (let [i (next-index counts before-count before-index)]
          (if (< i 0)
            0
            (let [count (vector-at counts i)
                  line (string-concat (string-from-i64 count)
                         (string-concat " " (string-concat (word-at text (vector-at starts i)) "\n")))
                  written (typed-cap-call :io/write :string :string line)]
              (recur (- left 1) count i))))))))

(defn- wordfreq [text :string limit :i64] :i64
  (let [lower (string-fold-case text)]
    (->> lower
         (word-starts)
         (top-n lower limit))))

(defn main [] :i64
  (wordfreq "To be, or not to be. That is the question. To be!" 10))
