(ns user
  "REPL development helpers. Load all services and provide start!/stop!/reset!."
  (:refer-clojure :exclude [reset!])
  (:require [clojure.tools.logging :as log]))

;; Lazy-load service namespaces to avoid compile errors when not all deps are on classpath
(defn- require-ns [sym]
  (try
    (require sym)
    true
    (catch Exception _
      false)))

(defn start!
  "Start all services that are on the classpath."
  []
  (log/info "Starting development services...")
  (when (require-ns 'ajet.chat.api.core)
    ((resolve 'ajet.chat.api.core/start!))
    (log/info "API service started"))
  (when (require-ns 'ajet.chat.auth-gw.core)
    ((resolve 'ajet.chat.auth-gw.core/start!))
    (log/info "Auth Gateway started"))
  (when (require-ns 'ajet.chat.web.core)
    ((resolve 'ajet.chat.web.core/start!))
    (log/info "Web SM started"))
  (when (require-ns 'ajet.chat.tui-sm.core)
    ((resolve 'ajet.chat.tui-sm.core/start!))
    (log/info "TUI SM started"))
  (log/info "All services started."))

(defn stop!
  "Stop all running services."
  []
  (log/info "Stopping development services...")
  (when (find-ns 'ajet.chat.tui-sm.core)
    ((resolve 'ajet.chat.tui-sm.core/stop!)))
  (when (find-ns 'ajet.chat.web.core)
    ((resolve 'ajet.chat.web.core/stop!)))
  (when (find-ns 'ajet.chat.auth-gw.core)
    ((resolve 'ajet.chat.auth-gw.core/stop!)))
  (when (find-ns 'ajet.chat.api.core)
    ((resolve 'ajet.chat.api.core/stop!)))
  (log/info "All services stopped."))

(defn reset!
  "Stop, reload, and restart all services."
  []
  (stop!)
  (start!))

;; Auto-start all services when the REPL loads
(try
  (start!)
  (catch Exception e
    (log/error e "Failed to auto-start services — REPL is still available. Fix the issue and run (start!)")
    (println "\n*** AUTO-START FAILED ***")
    (println "Error:" (.getMessage e))
    (println "REPL is ready — fix the issue and run (start!) manually.\n")))

(comment
  ;; After code changes:
  (reset!)
  ;; Stop services:
  (stop!)

  ;; Start individual services:
  (require 'ajet.chat.api.core)
  (ajet.chat.api.core/start!)
  (ajet.chat.api.core/stop!)
  )
