#!/usr/bin/guile -s
!#

(load "psyk.ss")

(define (read-input)
  (let ((input (string->list (read-line))))
    (if (treat-special-command input) #f input)))

(define (treat-special-command cmd)
  (cond ((null? cmd) #t)
	((eqv? (car cmd) #\#)
	 (let ((handler (assoc (list->string (prefix-word (cdr cmd)))
			       special-command-handlers)))
	   (if handler ((cadr handler) (skip-whitespace (skip-word (cdr cmd))))
	     (begin (display "Unknown command: ")
		    (display (list->string cmd)) (newline)
		    (display "Type '#help'.") (newline) #t))))
	(else #f)))

(define (react! input context)
  (let* ((new-context (update-context (make-context input) context))
	 (answer (get-answer new-context)))
    (display answer) (newline)
    (mark-used! answer)
    (learn! input context)
    (update-context (make-context answer) new-context)))

(define (mainloop context)
  (cond ((read-input) =>
	   (lambda (input) (mainloop (react! input context))))
	(else (mainloop context))))

(define (run init-line)
  (load-answers! "answers.db")
  (display init-line) (newline)
  (mainloop (make-context init-line)))

(run "Mistä haluaisit puhua?")
