 (defn fetch-all-stage-history [pipeline stage]
   (get-stage-instances pipeline stage 0))
 
-(defn job-instances-for-stage [load-builds-from {stage-name :stage pipeline :pipeline}]
+(defn job-instances-for-stage [load-builds-from accumulate-stages-for-pipelines {stage-name :stage pipeline :pipeline}]
   (let [safe-build-start-date (t/minus load-builds-from (t/millis 1))]
     (->> stage-name
          (fetch-all-stage-history pipeline)
-         (mapcat job-instances-for-stage-instance)
+         (mapcat (partial fetch-job-instances-for-stage-instance accumulate-stages-for-pipelines pipeline))
          (take-while #(t/after? (:scheduledDateTime %) safe-build-start-date))
          (map #(assoc % :stageName stage-name :pipelineName pipeline)))))
 

  (println "Go" go-url "-> buildviz" buildviz-url)

  (let [load-builds-from (get-start-date (:load-builds-from (:options args)))
        selected-pipeline-group-names (set (drop 1 (:arguments args)))
        pipeline-groups (get-pipeline-groups)
        selected-pipeline-groups (if (seq selected-pipeline-group-names)

  (let [build (get-json "/jobStatus.json?pipelineName=&stageName=&jobId=%s" jobId)]
    (parse-build-info build)))

(defn accumulate-builds [builds]
  (let [outcomes (map :outcome builds)
        start-times (map :start builds)
        end-times (map :end builds)]
    {:start (apply min start-times)
     :end (apply max end-times)
     :outcome (if (every? #(= "pass" %) outcomes)
                "pass"
                "fail")}))

(defn build-for-job [job-instance]
  (if-let [jobs-for-accumulation (:jobs-for-accumulation job-instance)]
    (let [builds (map build-for jobs-for-accumulation)]
      (accumulate-builds builds))
    (build-for job-instance)))

(defn job-data-for-instance [jobInstance]
  (assoc jobInstance :build (build-for-job jobInstance)))


;; /api/stages/%pipeline/%stage/history
