;; =============================================================================
;; Automated Smoke Test for Paw & Crown Cute 2D Multiplayer Chess
;; Verifies:
;;   1. Casual Room Lobby (wait for 2 players, spectator mode, legal & impossible moves, checkmate)
;;   2. Multi-Room Creation & Isolation (1 Room = 1 Game)
;;   3. Coming Back to an Ongoing Game (/api/room/reclaim across devices/sessions)
;;   4. Parallel Tournament Engine (4-Player Knockout: SF1 & SF2 played in parallel -> Auto-Spawn Final -> Champion)
;;   5. Headless WASM Frontend UI Rendering (Active Board, Rooms Lobby, Parallel Tournament Multi-Board View)
;; =============================================================================

(require "libs/str/src/str.coni" :as str)
(require "libs/os/src/io.coni" :as io)
(require "libs/os/src/shell.coni" :as shell)

(def base-url "http://localhost:3080")

(defn assert-eq [label actual expected]
  (if (= actual expected)
    (println (str "  ✅ PASS: " label " => " (pr-str actual)))
    (do
      (println (str "  ❌ FAIL: " label " | expected: " (pr-str expected) " | got: " (pr-str actual)))
      (sys-exit 1))))

(defn assert-true [label cond-val]
  (if cond-val
    (println (str "  ✅ PASS: " label))
    (do
      (println (str "  ❌ FAIL: " label))
      (sys-exit 1))))

(defn post-edn [path payload]
  (let [tmp-in "data/req_tmp.edn"
        _ (io/write-file tmp-in (pr-str payload))
        cmd (str "curl -s -X POST -H 'Content-Type: application/edn' --data-binary @" tmp-in " " base-url path)
        res (shell/sh cmd)]
    (io/delete-file tmp-in)
    (read-string (or (:stdout res) (get res "stdout")))))

(println "=== 🐾👑 Part A: Room Lobby, Move Validation & Checkmate Smoke Test ===")

;; 0. Reset room-paw-1 to clean state and verify Official FIDE Time Controls
(let [st (post-edn "/api/new-game" {:room-id "room-paw-1" :keep-players false})]
  (assert-eq "Initial status is waiting" (:status st) "waiting")
  (assert-eq "No white player yet" (get-in st [:players :w]) nil)
  (assert-eq "No black player yet" (get-in st [:players :b]) nil))

;; 0b. Test Official FIDE Rapid 15+10 and Custom 5+3 Time Controls
(let [tc15 (post-edn "/api/room/time-control" {:room-id "room-paw-1" :time-control "15+10"})]
  (assert-eq "Official Rapid 15+10 ID set" (get-in tc15 [:time-control :id]) "15+10")
  (assert-eq "Official Rapid 15+10 base-min is 15" (get-in tc15 [:time-control :base-min]) 15)
  (assert-eq "Official Rapid 15+10 inc-sec is 10" (get-in tc15 [:time-control :inc-sec]) 10)
  (assert-eq "Initial White clock is 900,000 ms (15m)" (get-in tc15 [:clocks :w-ms]) 900000))

(let [tc-custom (post-edn "/api/room/time-control" {:room-id "room-paw-1" :base-min 10 :inc-sec 5})]
  (assert-eq "Custom 10+5 ID set" (get-in tc-custom [:time-control :id]) "10+5")
  (assert-eq "Initial White clock is 600,000 ms (10m)" (get-in tc-custom [:clocks :w-ms]) 600000))

;; 1. Player 1 ("Mochi") enters name and joins -> game waits for 2nd player
(let [res1 (post-edn "/api/join" {:room-id "room-paw-1" :client-id "cid-mochi" :name "Mochi" :seat "auto"})]
  (assert-eq "Mochi assigned White" (:assigned-role res1) "w")
  (assert-eq "White player name is Mochi" (get-in res1 [:players :w :name]) "Mochi")
  (assert-eq "Status remains waiting for 2nd player" (:status res1) "waiting"))

;; 2. Player 1 tries to move before Player 2 joins -> blocked
(let [early-move (post-edn "/api/move" {:room-id "room-paw-1" :client-id "cid-mochi" :from [6 4] :to [4 4]})]
  (assert-eq "Cannot move while waiting for 2 players" (:ok early-move) false))

;; 3. Player 2 ("Boba") enters name and joins -> 2 players seated -> game starts!
(let [res2 (post-edn "/api/join" {:room-id "room-paw-1" :client-id "cid-boba" :name "Boba" :seat "auto"})]
  (assert-eq "Boba assigned Black" (:assigned-role res2) "b")
  (assert-eq "Black player name is Boba" (get-in res2 [:players :b :name]) "Boba")
  (assert-eq "Status transitions to playing!" (:status res2) "playing")
  (let [e2-moves (get (:legal-moves res2) "6,4")
        g1-moves (get (:legal-moves res2) "7,6")]
    (assert-eq "White e2 pawn has 2 highlighted legal moves" (count e2-moves) 2)
    (assert-eq "White g1 knight has 2 highlighted legal moves" (count g1-moves) 2)))

;; 4. Visitor 3 ("Kiki") arrives while game is in progress -> watches as Spectator!
(let [res3 (post-edn "/api/join" {:room-id "room-paw-1" :client-id "cid-kiki" :name "Kiki" :seat "auto"})]
  (assert-eq "3rd visitor assigned spectator role" (:assigned-role res3) "spectator")
  (assert-eq "Spectator list has 1 spectator" (count (:spectators res3)) 1))

;; 5. Impossible move detection tests
(let [bad-pawn (post-edn "/api/move" {:room-id "room-paw-1" :client-id "cid-mochi" :from [6 4] :to [5 5]})
      bad-knight (post-edn "/api/move" {:room-id "room-paw-1" :client-id "cid-mochi" :from [7 6] :to [5 6]})]
  (assert-eq "Diagonal pawn move to empty square detected as impossible" (:impossible bad-pawn) true)
  (assert-eq "Vertical knight move detected as impossible" (:impossible bad-knight) true))

;; 6. Coming Back to an Ongoing Game (Reclaim Seat from a new device/session!)
(println "\n=== 🔑 Part B: Multi-Room & Coming Back to a Game (Seat Reclaim) ===")
(let [reclaim-res (post-edn "/api/room/reclaim" {:room-id "room-paw-1" :color "w" :client-id "cid-mochi-phone" :name "Mochi"})]
  (assert-eq "Reclaim seat succeeds" (:ok reclaim-res) true)
  (assert-eq "White seat now linked to cid-mochi-phone" (get-in reclaim-res [:players :w :id]) "cid-mochi-phone"))

;; Play Fool's Mate using reclaimed seat cid-mochi-phone and verify Fischer +5s increment!
(let [m1 (post-edn "/api/move" {:room-id "room-paw-1" :client-id "cid-mochi-phone" :from [6 5] :to [5 5]})]
  (assert-true "Fischer +5s increment added to White's clock (> 600,000 ms)" (> (get-in m1 [:clocks :w-ms]) 600000)))
(post-edn "/api/move" {:room-id "room-paw-1" :client-id "cid-boba" :from [1 4] :to [3 4]})
(post-edn "/api/move" {:room-id "room-paw-1" :client-id "cid-mochi-phone" :from [6 6] :to [4 6]})
(def *final-mate-state* (post-edn "/api/move" {:room-id "room-paw-1" :client-id "cid-boba" :from [0 3] :to [4 7]}))
(let [m4 *final-mate-state*]
  (assert-eq "2... Qh4# succeeds" (:ok m4) true)
  (assert-eq "Game status is CHECKMATE!" (:status m4) "checkmate")
  (assert-eq "Winner name is Boba" (:winner-name m4) "Boba")
  (assert-eq "Move notation has checkmate #" (:notation (:last-move m4)) "Qh4#"))

;; Create a separate room and verify it starts fresh and isolated
(let [new-rm-res (post-edn "/api/room/create" {:name "Matcha Room" :client-id "cid-yuzu" :player-name "Yuzu" :auto-join true})
      new-rid (:created-room-id new-rm-res)]
  (assert-true "Created new room ID" (and new-rid (not= new-rid "")))
  (assert-eq "New room has Yuzu seated as White" (get-in new-rm-res [:players :w :name]) "Yuzu")
  (assert-eq "New room is waiting for 2nd player while room-paw-1 is checkmate" (:status new-rm-res) "waiting")
  (post-edn "/api/room/delete" {:room-id new-rid}))

;; ── Part C: Parallel Tournament Engine (SF1 & SF2 in Parallel -> Auto-Final) ──

(println "\n=== 🏆 Part C: Parallel Tournament Engine (Simultaneous Games & Auto-Bracket) ===")
(let [t-res (post-edn "/api/tournament/create"
              {:name "Paw Cup"
               :format "knockout-4"
               :players [{:id "p-mochi" :name "Mochi"}
                         {:id "p-boba" :name "Boba"}
                         {:id "p-kiki" :name "Kiki"}
                         {:id "p-yuzu" :name "Yuzu"}]
               :auto-start true})
      tid (:tournament-id t-res)
      tourney (get-in t-res [:tournaments tid])
      matches (:matches tourney)
      sf1 (nth matches 0)
      sf2 (nth matches 1)
      fin (nth matches 2)
      sf1-room-id (:room-id sf1)
      sf2-room-id (:room-id sf2)]
  (assert-eq "Tournament status is playing" (:status tourney) "playing")
  (assert-eq "Semifinal #1 is playing in parallel" (:status sf1) "playing")
  (assert-eq "Semifinal #2 is playing in parallel" (:status sf2) "playing")
  (assert-true "Both SF1 and SF2 have dedicated live rooms" (and sf1-room-id sf2-room-id (not= sf1-room-id sf2-room-id)))
  (assert-eq "Final is pending until SF1 & SF2 finish" (:status fin) "pending")

  ;; Play moves in parallel across SF1 and SF2 simultaneously!
  (let [sf1-m1 (post-edn "/api/move" {:room-id sf1-room-id :client-id "p-mochi" :from [6 4] :to [4 4]})
        sf2-m1 (post-edn "/api/move" {:room-id sf2-room-id :client-id "p-kiki" :from [6 3] :to [4 3]})]
    (assert-eq "Move 1 in SF1 (e4) succeeds while SF2 is ongoing" (:ok sf1-m1) true)
    (assert-eq "Move 1 in SF2 (d4) succeeds in parallel" (:ok sf2-m1) true))

  ;; Finish SF1 (Boba resigns -> Mochi advances to Final slot 1)
  (let [after-sf1 (post-edn "/api/resign" {:room-id sf1-room-id :client-id "p-boba"})
        t-mid (get-in after-sf1 [:tournaments tid])
        fin-mid (nth (:matches t-mid) 2)]
    (assert-eq "Mochi slotted into Final p1" (get-in fin-mid [:p1 :name]) "Mochi")
    (assert-eq "Final still waiting for SF2 winner" (:room-id fin-mid) nil))

  ;; Finish SF2 (Yuzu resigns -> Kiki advances -> Final Room spawns automatically!)
  (let [after-sf2 (post-edn "/api/resign" {:room-id sf2-room-id :client-id "p-yuzu"})
        t-ready (get-in after-sf2 [:tournaments tid])
        fin-ready (nth (:matches t-ready) 2)
        fin-room-id (:room-id fin-ready)]
    (assert-eq "Kiki slotted into Final p2" (get-in fin-ready [:p2 :name]) "Kiki")
    (assert-eq "Final match status automatically transitions to playing!" (:status fin-ready) "playing")
    (assert-true "Final room automatically spawned" (some? fin-room-id))

    ;; Finish Final (Kiki resigns -> Mochi crowned Tournament Champion!)
    (let [after-fin (post-edn "/api/resign" {:room-id fin-room-id :client-id "p-kiki"})
          t-done (get-in after-fin [:tournaments tid])]
      (assert-eq "Tournament status is completed" (:status t-done) "completed")
      (assert-eq "Tournament Champion is Mochi!" (:champion t-done) "Mochi")))

  ;; Clean up test tournament
  (post-edn "/api/tournament/delete" {:tournament-id tid}))

;; ── Part D: Headless WASM Frontend UI Render & Multi-View Verification ──────

(println "\n=== 🎨 Part D: Headless WASM Frontend UI (Board, Rooms, Tournaments) ===")

(def *dom-seq* (atom 0))
(def js/global (fn [target] target))
(def js/document "document")
(def js/new (fn [& _] "mock-obj"))
(def js/set (fn [& _] nil))
(def js/get (fn [target prop]
  (cond
    (= prop "value") "Mochi"
    (= prop "childNodes") "mock-children"
    :else nil)))
(def js/call (fn [target method & args]
  (cond
    (and (= target "document") (= method "createElement"))
    (str "el-" (swap! *dom-seq* inc))
    (and (= target "document") (= method "createElementNS"))
    (str "svg-" (swap! *dom-seq* inc))
    (and (= target "document") (= method "createTextNode"))
    (str "txt-" (swap! *dom-seq* inc))
    (and (= target "document") (= method "getElementById"))
    (first args)
    :else nil)))

(let [src (io/read-file "frontend/main.coni")
      non-blocking-src (str/replace src "(<! (chan 1))" ";; non-blocking test mode")
      tmp-path "data/frontend_test_runner.coni"]
  (io/write-file tmp-path non-blocking-src)
  (load-file tmp-path)
  (io/delete-file tmp-path))

(reset! *game* *final-mate-state*)
(reset! *nav-view* "board")
(render-ui)
(reset! *nav-view* "rooms")
(render-ui)
(reset! *nav-view* "tournaments")
(render-ui)
(println "  ✅ PASS: All 3 Views (Active Board, Rooms Grid, Parallel Tournament Studio) rendered cleanly!")

;; Reset default room back to clean waiting state for live users
(post-edn "/api/new-game" {:room-id "room-paw-1" :keep-players false})
(println "\n=== 🎉 ALL MULTI-ROOM, RESUME & PARALLEL TOURNAMENT TESTS PASSED! ===")
