name: Macro Release

on:
  release:
    types: [published]
  # Note: Only trigger on release.published to avoid duplicate runs.
  # Creating a release implicitly pushes a tag, so triggering on both
  # would cause the workflow to run twice.

# Cancel in-progress runs for the same tag
concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  package-macros:
    name: Package FreeCAD Macros
    runs-on: ubuntu-latest
    permissions:
      contents: write

    steps:
      - name: Checkout code
        uses: actions/checkout@v6

      - name: Get version from tag
        id: version
        run: |
          TAG="${GITHUB_REF#refs/tags/}"
          echo "tag=$TAG" >> "$GITHUB_OUTPUT"

          # Extract version without 'v' prefix
          VERSION="${TAG#v}"
          echo "version=$VERSION" >> "$GITHUB_OUTPUT"

          echo "Packaging macros for version: $VERSION"

      - name: Update macro versions
        run: |
          VERSION="${{ steps.version.outputs.version }}"
          TODAY=$(date +%Y-%m-%d)

          echo "Updating macros to version: $VERSION (date: $TODAY)"

          # Update __Version__ and __Date__ in all .FCMacro files
          for macro_file in macros/*/*.FCMacro; do
              if [ -f "$macro_file" ]; then
                  echo "Updating: $macro_file"

                  # Update __Version__ line (handles both single and double quotes)
                  sed -i "s/^__Version__ = [\"'].*[\"']/__Version__ = \"${VERSION}\"/" "$macro_file"

                  # Update __Date__ line (handles both single and double quotes)
                  sed -i "s/^__Date__ = [\"'].*[\"']/__Date__ = \"${TODAY}\"/" "$macro_file"

                  # Verify the changes
                  grep -E "^__(Version|Date)__" "$macro_file" || true
              fi
          done

      - name: Create macro archive
        run: |
          VERSION="${{ steps.version.outputs.version }}"

          # Create a staging directory
          mkdir -p "staging/freecad-macros-${VERSION}"

          # Copy macro directories (excluding test files and development artifacts)
          for macro_dir in macros/*/; do
              if [ -d "$macro_dir" ]; then
                  macro_name=$(basename "$macro_dir")
                  echo "Packaging macro: $macro_name"

                  # Create destination directory
                  mkdir -p "staging/freecad-macros-${VERSION}/${macro_name}"

                  # Copy macro files (.FCMacro, .py, .svg icons, README*, LICENSE*)
                  find "$macro_dir" -maxdepth 1 \( \
                      -name "*.FCMacro" -o \
                      -name "*.py" -o \
                      -name "*.svg" -o \
                      -name "README*" -o \
                      -name "LICENSE*" \
                  \) -exec cp {} "staging/freecad-macros-${VERSION}/${macro_name}/" \;
              fi
          done

          # Copy top-level LICENSE file
          if [ -f "LICENSE" ]; then
            cp LICENSE "staging/freecad-macros-${VERSION}/"
          else
            echo "ERROR: No LICENSE file found at repository root"
            exit 1
          fi

          # Add a top-level README
          cat > "staging/freecad-macros-${VERSION}/README.md" << 'EOF'
          # FreeCAD Macros

          This archive contains FreeCAD macros from the freecad-mcp project.

          ## Installation

          ### Macro Files

          Copy the macro files (`.FCMacro`) to your FreeCAD macro directory:

          - **macOS**: `~/Library/Application Support/FreeCAD/Macro/`
          - **Linux**: `~/.local/share/FreeCAD/Macro/`
          - **Windows**: `%APPDATA%/FreeCAD/Macro/`

          ### Icons (Optional)

          To display custom icons in the FreeCAD macro menu, copy the `.svg` files
          to your FreeCAD macro directory alongside the `.FCMacro` files.

          The icon file must have the same base name as the macro (e.g.,
          `CutObjectForMagnets.FCMacro` and `CutObjectForMagnets.svg`).

          ## Included Macros

          EOF

          # List included macros in the README
          for macro_dir in "staging/freecad-macros-${VERSION}/"*/; do
              if [ -d "$macro_dir" ]; then
                  macro_name=$(basename "$macro_dir")
                  echo "- **${macro_name}**: See ${macro_name}/README*.md for details" >> "staging/freecad-macros-${VERSION}/README.md"
              fi
          done

          cat >> "staging/freecad-macros-${VERSION}/README.md" << 'EOF'

          ## More Information

          For full documentation, visit:
          https://github.com/spkane/freecad-robust-mcp-and-more

          ## License

          MIT License - see LICENSE file included in this archive.
          EOF

          # Create the tar.gz archive
          cd staging
          tar -czvf "freecad-macros-${VERSION}.tar.gz" "freecad-macros-${VERSION}"

          # Also create a zip for Windows users
          zip -r "freecad-macros-${VERSION}.zip" "freecad-macros-${VERSION}"

          # Move archives to workspace root
          mv "freecad-macros-${VERSION}.tar.gz" ../
          mv "freecad-macros-${VERSION}.zip" ../

          cd ..
          echo "Created archives:"
          ls -la "freecad-macros-${VERSION}."*

      - name: Upload macro archives to release
        uses: softprops/action-gh-release@v2
        with:
          files: |
            freecad-macros-${{ steps.version.outputs.version }}.tar.gz
            freecad-macros-${{ steps.version.outputs.version }}.zip
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Generate summary
        run: |
          VERSION="${{ steps.version.outputs.version }}"

          {
            echo "## FreeCAD Macros Release"
            echo ""
            echo "**Version:** ${VERSION}"
            echo ""
            echo "### Packaged Macros"
            echo ""
          } >> "$GITHUB_STEP_SUMMARY"

          for macro_dir in macros/*/; do
              if [ -d "$macro_dir" ]; then
                  macro_name=$(basename "$macro_dir")
                  echo "- ${macro_name}" >> "$GITHUB_STEP_SUMMARY"
              fi
          done

          {
            echo ""
            echo "### Download"
            echo ""
            echo "The macro archives have been attached to the GitHub release:"
            echo ""
            echo "- \`freecad-macros-${VERSION}.tar.gz\` (Linux/macOS)"
            echo "- \`freecad-macros-${VERSION}.zip\` (Windows)"
          } >> "$GITHUB_STEP_SUMMARY"
