name: Link Language Check

on:
  workflow_call:
    inputs:
      soft-fail:
        description: 'Whether to continue on language path violations'
        required: false
        type: boolean
        default: false

permissions:
  contents: read

jobs:
  link-lang-check:
    name: Check for Language Paths in URLs
    runs-on: ubuntu-latest
    permissions:
      contents: read
    steps:
      - name: Checkout code
        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v4.2.2
        with:
          persist-credentials: false

      - name: Create logs directory
        shell: pwsh
        run: |
          New-Item -ItemType Directory -Force -Path logs | Out-Null

      - name: Run Link Language Check
        shell: pwsh
        run: |
          & scripts/linting/Invoke-LinkLanguageCheck.ps1 -ExcludePaths 'scripts/tests/**'
        continue-on-error: true

      - name: Upload results
        if: always()
        uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v4.4.3
        with:
          name: link-lang-check-results
          path: logs/link-lang-check-results.json
          retention-days: 30

      - name: Check results and fail if needed
        if: ${{ !inputs.soft-fail }}
        shell: pwsh
        run: |
          if ($env:LINK_LANG_FAILED -eq 'true') {
            $resultsPath = 'logs/link-lang-check-results.json'

            if (Test-Path -LiteralPath $resultsPath) {
              try {
                $results = Get-Content -LiteralPath $resultsPath -Raw | ConvertFrom-Json
                $totalIssues = [int]($results.summary.total_issues)
                $filesAffected = [int]($results.summary.files_affected)

                if ($results.issues -and $results.issues.Count -gt 0) {
                  if ($totalIssues -le 0) {
                    $totalIssues = [int]$results.issues.Count
                  }

                  if ($filesAffected -le 0) {
                    $filesAffected = [int](($results.issues | Select-Object -ExpandProperty file -Unique).Count)
                  }

                  Write-Host "❌ Link language check failed with $totalIssues issue(s) in $filesAffected file(s)."

                  foreach ($issue in $results.issues) {
                    Write-Host "  ⚠️ $($issue.file):$($issue.line_number) - $($issue.original_url)"
                  }
                } else {
                  Write-Host 'Link language check failed and no issue entries were found in logs/link-lang-check-results.json.'
                }
              } catch {
                Write-Host 'Link language check failed and logs/link-lang-check-results.json could not be parsed.'
              }
            } else {
              Write-Host 'Link language check failed and logs/link-lang-check-results.json was not found.'
            }

            exit 1
          }
