#!/bin/bash

set -e

# Help message
show_help() {
    echo "Usage: $0 [OPTIONS]"
    echo
    echo "Options:"
    echo "  --ref REF    Specify the git ref (branch, tag, or commit) to use from glockenspiel repository"
    echo "              Default: main"
    echo "  --help      Show this help message"
    echo
    echo "This script fetches the schema.json from the glockenspiel repository and generates Swift API code."
}

# Parse command line arguments
REF="main"
while [[ "$#" -gt 0 ]]; do
    case $1 in
        --ref) REF="$2"; shift ;;
        --help) show_help; exit 0 ;;
        *) echo "Unknown parameter: $1"; echo "Use --help to see available options"; exit 1 ;;
    esac
    shift
done

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/.."
OPENAPI_WORKING_DIR="${ROOT}/openapi"

pushd "$OPENAPI_WORKING_DIR"

# fetch latest glockenspiel

if command -v gh &> /dev/null && gh auth status &> /dev/null; then
    github_response=$(gh api "/repos/suno-ai/glockenspiel/contents/studio_api/schema.json?ref=$REF")
    download_url=$(echo "$github_response" | jq -r '.download_url')
    echo "$github_response" | jq -r '.sha' > glockenspiel_sha.txt

    if [ -z "$download_url" ]; then
        echo "Error: Could not extract download URL from the response"
        exit 1
    else
        rm schema.json
        if curl -L "$download_url" -o schema.json; then
            echo "Successfully downloaded schema.json from ref: $REF"
        else
            echo "Error: Failed to download the file"
            exit 1
        fi
    fi
else
    echo "Error: GitHub CLI is not installed or not logged in. not downloading the latest version, you need to fetch it yourself"
fi

# generate swift

sed -i '' 's#"openapi": "3.1.0"#"openapi": "3.0.1"#' schema.json
swift package plugin --allow-writing-to-package-directory create-api

set +e