' --- Workflow Library ---
'

EXPORT MODULE WFLIB

' Function: get_ngrok_url()
' Description: Retrieves the public URL from the local ngrok agent API.
EXPORT FUNC get_ngrok_url()

    API_URL$ = "http://127.0.0.1:4040/api/tunnels"

    ' To ensure the API returns JSON, we set the "Accept" header.
    HTTP.CLEARHEADERS()
    HTTP.SETHEADER "Accept", "application/json"

    TRY
        ' 1. Get the response from the API.
        RESPONSE$ = HTTP.GET$(API_URL$)

        ' 2. Parse the JSON string into a navigable JsonObject.
        RESPONSE_JSON = JSON.PARSE$(RESPONSE$)

        ' 3. Check if the object exist before access.
        IF LEN(RESPONSE_JSON) = 0 THEN
            PRINT "Error: JSON response is invalid ."
            PUBLIC_URL$ = ""
            GOTO EXIT_ME
        ENDIF

        TRY
            tunnels_array = RESPONSE_JSON{"tunnels"}
            IF LEN(tunnels_array)[0] = 0 THEN
                PRINT "Error: The 'tunnels' array in the JSON response is empty."
                PUBLIC_URL$ = ""
                GOTO EXIT_ME
            ENDIF
        CATCH
            PRINT "Error: The 'tunnels' key does not exist."
            PUBLIC_URL$ = ""
            GOTO EXIT_ME
        ENDTRY

        ' 4. Extract the public_url using modern chained access syntax.
        '    Path: Access the "tunnels" key, get the first element [0], then access the "public_url" key.
        PUBLIC_URL$ = RESPONSE_JSON{"tunnels"}[0]{"public_url"}

EXIT_ME:
        RETURN PUBLIC_URL$
    CATCH
        PRINT
        PRINT "*** An Error Occurred ***"
        PRINT "Could not connect to the ngrok agent at: "; API_URL$
        PRINT "Error Message: "; ERRMSG$
        PRINT "Please make sure the ngrok agent is running."
        RETURN ""
    ENDTRY

ENDFUNC
