;
(require-extension srfi-1)
(require-extension srfi-13)
(require-extension irnc-base)
(require-extension posix)

(define (get-page-contents wiki page)
  (and-let* (
    [page-contents-response
      (irnc-api wiki
		`((action . "query")
		  (prop . "revisions")
		  (titles . ,page)
		  (rvprop . "content")))]
    [page-contents-xml
      (and (not (null? page-contents-response))
	   (cdr page-contents-response))]
    [rev ((sxpath "api/query/pages/page/revisions/rev")
	    page-contents-xml)]
    [page-contents
      (and (not (null? rev))
	   (cadar rev))])
    page-contents))

(define (page-contains-pattern wiki page pattern)
  (and-let* (
    [page-contents (get-page-contents wiki page)])
    ;;(pretty-print content)
    (string-search pattern page-contents)))

(define (wiki-list lst)
  (let loop ([lst lst] [str ""])
    (if (null? lst) str
      (loop (cdr lst) (string-append str "* {{la|" (->string (car lst)) "}}\n")))))
	    

(define (articles-containing-spoilers wiki spoiler-list)
  (let* (
    [possible-spoilers
      (filter
	(lambda (article) (not (member article spoiler-list)))
	(irnc-search wiki "spoiler" 50000))]
    [spoilers
      (filter
	(lambda (page)
	  (page-contains-pattern wiki page "[Ss][Pp][Oo][Ii][Ll][Ee][Rr]"))
	possible-spoilers)])
    spoilers))

(define (wiki-heading level title)
  (let ([equals (make-string level #\=)])
    (string-append
      equals title equals "\n")))

(irnc-debug 0)
(let* (
      [config-file (string-append (getenv "HOME") "/.ironchicken")]
      [wiki (irnc-config config-file 'wiki)]
      [username (irnc-config config-file 'user)]
      [password (irnc-config config-file 'password)]
      [spoiler-file "./.spoilersrc"]
      [spoiler-list (with-input-from-file spoiler-file read)]
      [login-handle (irnc-login wiki username password)])
  (or login-handle
      (begin (display "Login failure")(newline)(exit)))
  (let ((edit-handle (irnc-edit login-handle "User:Tony Sidaway/spoilers")))
    (irnc-submit edit-handle
      (string-append
	(wiki-heading 2 "Pages unexpectedly containing the word \"spoiler\"")
	(wiki-list (articles-containing-spoilers wiki spoiler-list)))
      (string-append
	"List of pages unexpectedly containing the word \"spoiler\" "
	"compiled by " username " using " (irnc-user-agent)))))