#!/bin/bash

# First, get all project IDs
curl --request GET \
  --header "PRIVATE-TOKEN: $SELF_GITLAB_TOKEN" \
  "https://gitlab.ellisbs.co.uk/api/v4/projects?per_page=100" 2>/dev/null |
  jq -r '.[] | select(.id) | "\(.id) \(.path_with_namespace)"' |
  while read -r project_id project_path; do
    echo "Analyzing schedules for project: $project_path"

    # Get all pipeline schedules for this project
    schedules=$(curl --request GET \
      --header "PRIVATE-TOKEN: $SELF_GITLAB_TOKEN" \
      "https://gitlab.ellisbs.co.uk/api/v4/projects/${project_id}/pipeline_schedules" 2>/dev/null)

    # For each schedule, get its pipeline runs
    echo "$schedules" | jq -r '.[] | select(.id) | "\(.id) \(.description)"' |
      while read -r schedule_id description; do
        echo "  Analyzing schedule: $description"

        # Get pipelines for this schedule (last 100)
        pipelines=$(curl --request GET \
          --header "PRIVATE-TOKEN: $SELF_GITLAB_TOKEN" \
          "https://gitlab.ellisbs.co.uk/api/v4/projects/${project_id}/pipeline_schedules/${schedule_id}/pipelines?per_page=100" 2>/dev/null)

        # Calculate success rate
        total=$(echo "$pipelines" | jq -r '. | length')
        if [ "$total" -gt 0 ]; then
          success=$(echo "$pipelines" | jq -r '[.[] | select(.status == "success")] | length')
          rate=$(echo "scale=2; ($success * 100) / $total" | bc)
          echo "    Success rate: $rate% ($success successful out of $total runs)"
        else
          echo "    No pipeline runs found"
        fi
      done
    echo ""
  done
