;; Log Parser Example
;; Demonstrates text processing and simple analytics

(import assert :refer :all)
(import binding :refer :all)
(import control :refer :all)
(import dict :refer :all)
(import display :refer :all)
(import looping :refer :all)
(import strings :refer :all)
(import threading :refer :all)

(define log-lines
  (list
   "2026-01-01 GET /api/users 200 100"
   "2026-01-01 POST /api/login 500 110"
   "2026-01-01 GET /api/users 200 120"
   "2026-01-01 PUT /api/users 200 130"
   "2026-01-01 GET /api/orders 500 140"
   "2026-01-01 GET /api/orders 200 120"))

(define parse-line
  (lambda (line)
    (define parts (string-split line " "))
    (dict
     :date (nth parts 0)
     :method (nth parts 1)
     :path (nth parts 2)
     :status (as.numeric (nth parts 3))
     :latency (as.numeric (nth parts 4)))))

(define parsed (map parse-line log-lines))
(assert-equal 6 (length parsed))

(define statuses (map (lambda (row) (get "status" row)) parsed))
(define latencies (map (lambda (row) (get "latency" row)) parsed))
(assert-equal (list 200 500 200 200 500 200) statuses)
(assert-equal (list 100 110 120 130 140 120) latencies)

(define status-500 (length (filter (lambda (s) (= s 500)) statuses)))
(define avg-latency (/ (reduce + latencies) (length latencies)))
(assert-equal 2 status-500)
(assert-equal 120 avg-latency)

(println "=== Log Summary ===")
(assert-equal 6 (length log-lines))
(println (string-concat "Total lines: " (length log-lines)))
(println (string-concat "HTTP 500 count: " status-500))
(println (string-concat "Average latency: " avg-latency))

(println "\nExample complete!")
