name: Type Check Base
on:
  workflow_call:
    inputs:
      python-version:
        required: false
        type: string
        default: '3.14.0'

jobs:
  typecheck:
    name: Check
    runs-on: ubuntu-latest
    steps:
    - run: npm install toml
    - name: Get pyproject.toml
      uses: actions/github-script@v8
      id: get-pyproject
      with:
        github-token: ${{secrets.GITHUB_TOKEN}}
        script: |
          const ref = context.payload.pull_request ? context.payload.pull_request.head.sha : context.sha;
          const { data: pyprojectContent } = await github.rest.repos.getContent({
            owner: context.repo.owner,
            repo: context.repo.repo,
            path: 'pyproject.toml',
            ref: ref
          });
          const content = Buffer.from(pyprojectContent.content, 'base64').toString();
          const toml = require('toml');
          const parsed = toml.parse(content);
          const mypyFiles = parsed.tool?.mypy?.files ?? [];
          return { mypyFiles, content };

    - name: Check for changes in mypy files
      uses: actions/github-script@v8
      id: check-changes
      with:
        github-token: ${{secrets.GITHUB_TOKEN}}
        script: |
          const { mypyFiles } = ${{ steps.get-pyproject.outputs.result }};

          let changedMypyFiles = [];
  
          if (context.payload.pull_request) {
            const { data: changedFiles } = await github.rest.pulls.listFiles({
              owner: context.repo.owner,
              repo: context.repo.repo,
              pull_number: context.payload.pull_request.number
            });
            changedMypyFiles = changedFiles
              .filter(file => mypyFiles.includes(file.filename))
              .map(file => file.filename);
          } else {
            // If not a pull request, assume all mypy files are changed
            changedMypyFiles = mypyFiles;
          }
          return changedMypyFiles.length > 0;

    - name: Set up Python
      if: steps.check-changes.outputs.result == 'true'
      uses: actions/setup-python@v6
      with:
        python-version: ${{ inputs.python-version }}

    - uses: actions/checkout@v6
      if: steps.check-changes.outputs.result == 'true'
    
    - name: Cache pip
      uses: actions/cache@v4
      if: steps.check-changes.outputs.result == 'true'
      with:
        path: ~/.cache/pip
        key: ${{ runner.os }}-pip-typecheck-${{ hashFiles('**/*requirements.txt', '**/pyproject.toml', '**/setup.py') }}
        restore-keys: |
          ${{ runner.os }}-pip-typecheck-
          ${{ runner.os }}-pip-
          ${{ runner.os }}-

    - name: Install dependencies
      if: steps.check-changes.outputs.result == 'true'
      run: |
        python -m pip install --upgrade pip
        pip install -e .[dev,test]
        
    - name: Run mypy
      if: steps.check-changes.outputs.result == 'true'
      run: |
        mypy --version
        mypy
