{% import 'common.yml.j2' as common %}
{% import 'upload.yml.j2' as upload %}

{%- block name -%}
# Template is at:    .github/templates/macos_binary_build_workflow.yml.j2
# Generation script: .github/scripts/generate_ci_workflows.py
name: !{{ build_environment }}
{%- endblock %}

{%- macro set_runner_specific_vars() -%}
      # NOTE: These environment variables are put here so that they can be applied on every job equally
      #       They are also here because setting them at a workflow level doesn't give us access to the
      #       runner.temp variable, which we need.
      - name: Populate binary env
        shell: bash
        run: |
          # shellcheck disable=SC2129
          echo "BINARY_ENV_FILE=${RUNNER_TEMP}/env" >> "${GITHUB_ENV}"
          # shellcheck disable=SC2129
          echo "PYTORCH_FINAL_PACKAGE_DIR=${RUNNER_TEMP}/artifacts" >> "${GITHUB_ENV}"
          # shellcheck disable=SC2129
          echo "MAC_PACKAGE_WORK_DIR=${RUNNER_TEMP}" >> "${GITHUB_ENV}"
{%- endmacro %}

{%- macro setup_python(py_ver) -%}
      - name: Setup Python
        uses: actions/setup-python@v6
        with:
          # .4 version is min minor for 3.10, and also no-gil version of 3.13 needs at least 3.13.3
          python-version: "!{{ py_ver.strip('t') + ('.4' if '3.14' not in py_ver else '.0') }}"
          freethreaded: !{{ "true" if py_ver.endswith('t') else "false" }}
{%- endmacro %}

on:
# TODO: Migrate to new ciflow trigger, reference https://github.com/pytorch/pytorch/pull/70321
  push:
    # NOTE: Meta Employees can trigger new nightlies using: https://fburl.com/trigger_pytorch_nightly_build
    branches:
      - nightly
    tags:
      # NOTE: Binary build pipelines should only get triggered on release candidate builds
      # Release candidate tags look like: v1.11.0-rc1
      - v[0-9]+.[0-9]+.[0-9]+-rc[0-9]+
{%- for label in ciflow_config.labels | sort %}
    {%- if loop.first and branches != "nightly" %}
    tags:
    {%- endif %}
      - '!{{ label }}/*'
{%- endfor %}
  workflow_dispatch:

env:
  ALPINE_IMAGE: "308535385114.dkr.ecr.us-east-1.amazonaws.com/tool/alpine"
  AWS_DEFAULT_REGION: us-east-1
  BUILD_ENVIRONMENT: !{{ build_environment }}
  GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
  PR_NUMBER: ${{ github.event.pull_request.number }}
  SKIP_ALL_TESTS: 0
!{{ common.concurrency(build_environment) }}

jobs:
{%- for config in build_configs %}
  !{{ config["build_name"] }}-build:
    if: ${{ github.repository_owner == 'pytorch' }}
    runs-on: !{{ macos_runner }}
    timeout-minutes: !{{ common.timeout_minutes }}
    !{{ upload.binary_env(config, true) }}
    {%- if config.pytorch_extra_install_requirements is defined and config.pytorch_extra_install_requirements|d('')|length > 0  %}
      PYTORCH_EXTRA_INSTALL_REQUIREMENTS: !{{ config.pytorch_extra_install_requirements }}
    {%- endif %}
    steps:
      !{{ set_runner_specific_vars() }}
      !{{ setup_python(config.get("python_version", "3.10")) }}
      !{{ common.checkout(deep_clone=False) }}
      - name: Populate binary env
        run: |
          "${PYTORCH_ROOT}/.circleci/scripts/binary_populate_env.sh"
      - name: Build PyTorch binary
        run: |
          set -eux -o pipefail
          # shellcheck disable=SC1090
          source "${BINARY_ENV_FILE:-/Users/distiller/project/env}"
          mkdir -p "$PYTORCH_FINAL_PACKAGE_DIR"

          # Build
          USE_PYTORCH_METAL_EXPORT=1
          USE_COREML_DELEGATE=1
          TORCH_PACKAGE_NAME="${TORCH_PACKAGE_NAME//-/_}"
          export USE_PYTORCH_METAL_EXPORT
          export USE_COREML_DELEGATE
          export TORCH_PACKAGE_NAME
          "${PYTORCH_ROOT}/.ci/wheel/install_libomp.sh"
          "${PYTORCH_ROOT}/.ci/wheel/build_wheel.sh"
{%- if config["package_type"] == "wheel" %}
      - name: Test PyTorch wheel
        run: |
          set -eux -o pipefail
          # shellcheck disable=SC1090
          source "${BINARY_ENV_FILE:-/Users/distiller/project/env}"
          pip uninstall -y "$TORCH_PACKAGE_NAME" || true
          pip uninstall -y "$TORCH_PACKAGE_NAME" || true

          # Create new "clean" conda environment for testing

          SMOKE_TEST_PARAMS=""

          # shellcheck disable=SC2086
          python -mvenv test_venv
          source test_venv/bin/activate
          pip install "$PYTORCH_FINAL_PACKAGE_DIR"/*.whl numpy -v

          # shellcheck disable=SC2086
          python "${PYTORCH_ROOT}/.ci/pytorch/smoke_test/smoke_test.py" --package torchonly ${SMOKE_TEST_PARAMS}
{%- endif %}
      - uses: actions/upload-artifact@v4.4.0
        if: always()
        with:
          name: !{{ config["build_name"] }}
          retention-days: 14
          if-no-files-found: error
          path: "${{ env.PYTORCH_FINAL_PACKAGE_DIR }}"
  !{{ upload.upload_binaries(config, has_test=False, use_s3=False) }}
{%- endfor %}

{%- for lt_config in libtorch_extraction_configs %}
  !{{ lt_config["build_name"] }}-extract:
    if: ${{ github.repository_owner == 'pytorch' }}
    needs: !{{ lt_config["source_wheel_build_name"] }}-build
    runs-on: !{{ macos_runner }}
    timeout-minutes: 60
    env:
      DESIRED_CUDA: !{{ lt_config["desired_cuda"] }}
      LIBTORCH_VARIANT: !{{ lt_config["libtorch_variant"] }}
    steps:
      - name: Checkout PyTorch
        uses: actions/checkout@v4
        with:
          ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
          sparse-checkout: .ci/libtorch/
          show-progress: false
      !{{ setup_python("3.10") }}
      - uses: actions/download-artifact@v4.1.7
        name: Download Wheel Artifact
        with:
          name: !{{ lt_config["source_wheel_build_name"] }}
          path: "${{ runner.temp }}/wheel_artifact/"
      - name: Extract libtorch from wheel
        run: |
          set -eux
          mkdir -p "${{ runner.temp }}/libtorch_output"
          python3 .ci/libtorch/extract_libtorch_from_wheel.py \
            --wheel-dir "${{ runner.temp }}/wheel_artifact" \
            --output-dir "${{ runner.temp }}/libtorch_output" \
            --platform macos \
            --desired-cuda "$DESIRED_CUDA" \
            --libtorch-variant "$LIBTORCH_VARIANT"
      - uses: actions/upload-artifact@v4.4.0
        if: always()
        with:
          name: !{{ lt_config["build_name"] }}
          retention-days: 14
          if-no-files-found: error
          path: "${{ runner.temp }}/libtorch_output/"
  !{{ upload.upload_extracted_libtorch(lt_config, use_s3=False) }}
{%- endfor %}
