name: Label issues from dropdowns

on:
  issues:
    types: [opened]

jobs:
  label_from_dropdown:
    runs-on: ubuntu-latest
    permissions:
      issues: write
    steps:
      - name: Apply labels based on dropdown choices
        uses: actions/github-script@v7
        with:
          script: |

            const issueNumber = context.issue.number;
            const owner = context.repo.owner;
            const repo = context.repo.repo;

            // Get the issue body
            const body = context.payload.issue.body;

            // Helper to find dropdown value in the body (assuming markdown format)
            function extractSectionValue(heading) {
              const regex = new RegExp(`### ${heading}\\s+([\\s\\S]*?)(?:\\n###|$)`, 'i');
              const match = body.match(regex);
              if (match) {
                // Get the first non-empty line after the heading
                const lines = match[1].split('\n').map(l => l.trim()).filter(Boolean);
                return lines[0] || null;
              }
              return null;
            }

            // Extract dropdown selections
            const category = extractSectionValue('Category');
            const metrics = extractSectionValue('Affected Metrics');
            const component = extractSectionValue('Component');

            // Build labels to add
            let labelsToAdd = [];
            if (category) labelsToAdd.push(category);
            if (metrics) labelsToAdd.push(metrics);
            if (component) labelsToAdd.push(component);

            // Get existing labels in the repo
            const { data: existingLabels } = await github.rest.issues.listLabelsForRepo({
              owner,
              repo,
              per_page: 100
            });
            const existingLabelNames = existingLabels.map(l => l.name);

            // Find labels that need to be created
            const labelsToCreate = labelsToAdd.filter(label => !existingLabelNames.includes(label));

            // Create missing labels (with a default color)
            for (const label of labelsToCreate) {
              try {
                await github.rest.issues.createLabel({
                  owner,
                  repo,
                  name: label,
                  color: 'ededed' // light gray, you can pick any hex color
                });
              } catch (e) {
                // Ignore if label already exists (race condition), otherwise rethrow
                if (!e || e.status !== 422) throw e;
              }
            }

            // Now apply all labels (they all exist now)
            if (labelsToAdd.length > 0) {
              await github.rest.issues.addLabels({
                owner,
                repo,
                issue_number: issueNumber,
                labels: labelsToAdd
              });
            } 