(in-package #:lispsearch/test)

;;;; Catalog ingest (Tier 1): name parse/decode + sha (offline), full cold build
;;;; from the live catalog (network). (was test/m2-catalog.lisp)

(define-test catalog-parse :parent offline
  (let ((pairs (ls:parse-catalog
                (format nil "cl-ppcre~%cl_plus_ssl~%cl-ppcre~%~%  clog_slash_tools  ~%"))))
    (is = 3 (length pairs) "dedupes 3 unique from 4 lines")
    (is string= "cl_plus_ssl" (car (assoc "cl_plus_ssl" pairs :test #'string=))
        "keeps raw registry name")
    (is string= "cl+ssl" (cdr (assoc "cl_plus_ssl" pairs :test #'string=))
        "decodes _plus_ -> +")
    (is string= "clog/tools" (cdr (assoc "clog_slash_tools" pairs :test #'string=))
        "decodes _slash_ -> /")))

(define-test catalog-sha :parent offline
  (is string= (ls:catalog-sha "abc") (ls:catalog-sha "abc") "stable")
  (is = 32 (length (ls:catalog-sha "abc")) "hex length")
  (isnt string= (ls:catalog-sha "abc") (ls:catalog-sha "abd") "differs on change"))

(define-test catalog-build :parent network
  (with-fresh-db (db)
    (let ((loaded (ls:build-index db :enrich nil)))
      (true (> loaded 2000) "loaded the full catalog (>2000 systems)")
      (is = loaded (getf (ls:stats db) :total) "all loaded rows present")
      (is = 0 (getf (ls:stats db) :enriched) "every row enriched=0 (Tier 1)")
      (is = 32 (length (or (ls:meta-get db "catalog_sha") "")) "catalog_sha recorded")
      (true (plusp (length (or (ls:meta-get db "last_refresh") ""))) "last_refresh recorded"))
    (let* ((rows (ls:run-search db "trivial" :limit 1000 :names-only t))
           (names (mapcar #'first rows)))
      (true (> (length names) 5) "'trivial' returns many")
      (true (member "trivial-features" names :test #'string=))
      (true (member "trivial-gray-streams" names :test #'string=))
      (true (every (lambda (n) (search "trivial" n)) names) "every hit contains 'trivial'")
      (is equal names (sort (copy-list names) #'string<) "results sorted by name"))
    (let ((before (getf (ls:stats db) :total)))
      (ls:build-index db :enrich nil)
      (is = before (getf (ls:stats db) :total) "re-build is idempotent (no dup rows)"))))
