#! /bin/sh
#
# SPDX-FileType: SOURCE
# SPDX-License-Identifier: Apache-2.0
#
# Generate the per-version bindings and the bindings package __init__.py.

set -e

# SPDX versions to generate
SPDX_VERSIONS="3.0.1"

get_context_url() {
    echo "https://spdx.org/rdf/$1/spdx-context.jsonld"
}

# Generate the per-version bindings with shacl2code.
# Each version ends up in its own subpackage (e.g. "v3_0_1").
for v in $SPDX_VERSIONS; do
    MODNAME="v$(echo "$v" | sed 's/[^a-zA-Z0-9_]/_/g')"

    CONTEXT_URL="$(get_context_url "$v")"
    if [ -n "${SHACL2CODE_SPDX_DIR}" ] && [ -d "${SHACL2CODE_SPDX_DIR}/$v" ]
    then
        shacl2code generate --input "file://${SHACL2CODE_SPDX_DIR}/$v/spdx-model.ttl" \
            --input "file://${SHACL2CODE_SPDX_DIR}/$v/spdx-json-serialize-annotations.ttl" \
            --context-url "file://${SHACL2CODE_SPDX_DIR}/$v/spdx-context.jsonld" $CONTEXT_URL \
            --license Apache-2.0 \
            python \
            --output "$MODNAME"
    else
        shacl2code generate --input https://spdx.org/rdf/$v/spdx-model.ttl \
            --input https://spdx.org/rdf/$v/spdx-json-serialize-annotations.ttl \
            --context $CONTEXT_URL \
            --license Apache-2.0 \
            python \
            --output "$MODNAME"
    fi
done

# Generate the bindings package __init__.py.
{
    echo '# SPDX-FileType: SOURCE'
    echo '# SPDX-License-Identifier: Apache-2.0'
    echo '#'
    echo '# Generated by generate-bindings at build time. DO NOT EDIT.'
    echo '"""SPDX model bindings, one submodule per version.'
    echo
    echo 'Versions are not imported here, so importing one does not load the others.'
    echo '"""'
    echo
    echo '# JSON-LD @context URL -> version submodule name, for lazy lookup by load().'
    echo '_CONTEXT_TABLE = {'
    for v in $SPDX_VERSIONS; do
        MODNAME="v$(echo "$v" | sed 's/[^a-zA-Z0-9_]/_/g')"
        CONTEXT_URL="$(get_context_url "$v")"
        echo "    \"$CONTEXT_URL\": \"$MODNAME\","
    done
    echo '}'
} > __init__.py

# Generate _reexport.pyi: lets type checkers resolve spdx_python_model.vX types
# while the runtime loads versions lazily (imported only under TYPE_CHECKING).
{
    echo '# SPDX-FileType: SOURCE'
    echo '# SPDX-License-Identifier: Apache-2.0'
    echo '#'
    echo '# Generated by generate-bindings at build time. DO NOT EDIT.'
    echo '"""Type-checking-only re-exports so ``spdx_python_model.vX`` types resolve.'
    echo
    echo 'Imported under TYPE_CHECKING only; the runtime loads versions lazily via the'
    echo 'package __getattr__. __all__ marks the names as re-exports for --no-implicit-reexport.'
    echo '"""'
    for v in $SPDX_VERSIONS; do
        MODNAME="v$(echo "$v" | sed 's/[^a-zA-Z0-9_]/_/g')"
        echo "from . import $MODNAME"
    done
    echo
    echo '__all__ = ['
    for v in $SPDX_VERSIONS; do
        MODNAME="v$(echo "$v" | sed 's/[^a-zA-Z0-9_]/_/g')"
        echo "    \"$MODNAME\","
    done
    echo ']'
} > _reexport.pyi
