# Common artifact staging steps for release workflows
# Downloads build artifacts from pipeline and stages them for GitHub/Marketplace publication
# Used by: include-github-release.yml, include-marketplace-release.yml

parameters:
  - name: expectedVsixCount
    type: number
    default: 7

steps:
  # Download all artifacts produced by build (all vsix + manifests + signatures)
  - task: DownloadPipelineArtifact@2
    displayName: "Download build artifacts"
    inputs:
      itemPattern: |
        drop_Build_build_extension/*.vsix
        drop_Build_build_extension/*.manifest.json
        drop_Build_build_extension/*.signature.p7s
        drop_Build_build_extension/packaged-artifacts.json
      targetPath: $(Agent.TempDirectory)

  - task: Bash@3
    displayName: "Stage artifacts"
    inputs:
      targetType: inline
      script: |
        set -euo pipefail
        mkdir -p "$(Build.ArtifactStagingDirectory)"

        # Copy all required artifacts (fail fast if missing)
        echo "Copying VSIX files..."
        cp -v $(Agent.TempDirectory)/drop_Build_build_extension/*.vsix "$(Build.ArtifactStagingDirectory)/"

        echo "Copying manifest files..."
        cp -v $(Agent.TempDirectory)/drop_Build_build_extension/*.manifest.json "$(Build.ArtifactStagingDirectory)/"

        echo "Copying signature files..."
        cp -v $(Agent.TempDirectory)/drop_Build_build_extension/*.signature.p7s "$(Build.ArtifactStagingDirectory)/"

        # Artifact manifest is required for publication logic
        echo "Copying artifact manifest..."
        if [ ! -f $(Agent.TempDirectory)/drop_Build_build_extension/packaged-artifacts.json ]; then
          echo "ERROR: packaged-artifacts.json missing from build artifacts" >&2
          exit 1
        fi
        cp -v $(Agent.TempDirectory)/drop_Build_build_extension/packaged-artifacts.json "$(Build.ArtifactStagingDirectory)/"

        echo "Staged files:"; ls -1 "$(Build.ArtifactStagingDirectory)"
        count=$(ls -1 "$(Build.ArtifactStagingDirectory)"/*.vsix | wc -l)
        echo "Detected VSIX count: $count"
        if [ "$count" -ne ${{ parameters.expectedVsixCount }} ]; then
          echo "ERROR: Expected ${{ parameters.expectedVsixCount }} VSIX artifacts but found $count" >&2
          exit 1
        fi
