#!/usr/bin/env nextflow

/*
 * Test version extraction snippets for nf-core modules
 *
 * Usage:
 *   PROFILE=docker nextflow run test-version-extraction.nf \
 *     -c tests/config/nextflow.config \
 *     --m fastp \
 *     --s 'fastp --version 2>&1 | sed "s/fastp //"'
 */

params.m = null
params.s = null

if (!params.m || !params.s) {
    error "Please provide both --m and --s parameters"
}

// Read container from module's main.nf and extract Docker image
def moduleMainNf = file("${projectDir}/modules/nf-core/${params.m}/main.nf").text
// Extract Docker image (after the colon in the ternary operator)
def containerMatch = moduleMainNf =~ /(?s)container\s+"[^"]*:\s*\n?\s*'([^']+)'\s*}"/
def containerImage = containerMatch ? containerMatch[0][1] : null

if (!containerImage) {
    error "Could not extract container from module ${params.m}/main.nf"
}

process TEST_VERSION_EXTRACTION {
    label 'process_low'

    container containerImage

    output:
    stdout emit: result

    script:
    // Extract the base command (before first pipe) for raw output
    def baseCommand = params.s.split('\\|')[0].trim()
    """
    echo "Testing version extraction for module: ${params.m}"
    echo ""
    echo "Raw version output:"
    echo "---"
    ${baseCommand}
    echo ""
    echo "Processed output:"
    echo "Snippet: ${params.s}"
    echo "---"
    ${params.s}
    """
}

workflow {
    TEST_VERSION_EXTRACTION()
    TEST_VERSION_EXTRACTION.out.result.view()
}
