(ns auto-ap.background.metrics
  (:require [com.unbounce.dogstatsd.core :as statsd]
            [mount.core :as mount]
            [clj-http.client :as http]
            [auto-ap.logging :as alog]
            [config.core :refer [env]]
            [com.brunobonacci.mulog :as mu]
            [com.brunobonacci.mulog.common.json :as j]))

(defn get-container-data []
  (try
    (let [result
          (some-> env
                  (:ecs-container-metadata-uri-v4)
                  (http/get {:as :json})
                  :body)]
      result)
    (catch Exception e
      (alog/error ::no-container-tags
                  :error e)
      {})))

(mount/defstate container-data
  :start (get-container-data)
  :stop nil)

(defn get-container-tags []
  [(str "container:" (:DockerId container-data))
   (str "ip:" (-> container-data :Networks first :IPv4Addresses first))])


(mount/defstate container-tags
  :start (get-container-tags)
  :stop nil)

(defn capture-invalid-json
  [events]
  (filter
   (fn [event]
     (try
       (j/to-json event)
       true
       (catch Exception _
         (mu/log ::invalid-json-value :value (pr-str event))
         false)))
   events))

(defn set-logging-context []
  (when (seq container-data)

    (mu/start-publisher! {:type :console-json
                          :transform (fn [events]
                                       (->> events
                                            capture-invalid-json
                                            (map (fn [{:keys [mulog/duration mulog/event-name mulog/namespace] :as e}]
                                                   (cond-> e
                                                     duration (assoc :duration duration
                                                                     :duration-ms (quot duration 1000000))
                                                     true (assoc :event-name event-name
                                                                 :namespace namespace))))))})
    (mu/set-global-context!
     {:container (:DockerId container-data)
      :ip (-> container-data :Networks first :IPv4Addresses first)
      :env (:dd-env env)
      :service (or
                (System/getenv "INTEGREAT_JOB")
                (:dd-service env))})))

(defn stop-logging-context []
  (when (seq container-data)))

#_{:clj-kondo/ignore [:clojure-lsp/unused-public-var]}
(mount/defstate logging-context
  :start (set-logging-context)
  :stop (stop-logging-context))

#_{:clj-kondo/ignore [:clojure-lsp/unused-public-var]}
(mount/defstate metrics-setup
  :start (statsd/setup! :host "127.0.0.1" :port 8125 :prefix "integreat.app" :tags (into #{(str "env:" (:dd-env env))
                                                                                           (str "service:" (:dd-service env))}
                                                                                         container-tags))
  :stop (statsd/shutdown!))
