name: Create discord thread and comment on GitHub issue when script is ready for testing

on:
  issues:
    types:
      - labeled

permissions:
  issues: write

jobs:
  post_to_discord:
    runs-on: ubuntu-latest
    if: contains(github.event.issue.labels.*.name, 'Ready For Testing') && github.repository == 'community-scripts/ProxmoxVED'
    steps:
      - name: Extract Issue Title and Script Type
        id: extract_info
        env:
          ISSUE_BODY: ${{ github.event.issue.body }}
        run: |
          # Extract title (lowercase, spaces to dashes)
          TITLE=$(echo '${{ github.event.issue.title }}' | tr '[:upper:]' '[:lower:]' | sed 's/ /-/g')
          echo "TITLE=$TITLE" >> $GITHUB_ENV

          # Extract script type from issue body (using env var to handle special chars)
          if echo "$ISSUE_BODY" | grep -qi "CT (LXC Container)"; then
            SCRIPT_TYPE="ct"
          elif echo "$ISSUE_BODY" | grep -qi "VM (Virtual Machine)"; then
            SCRIPT_TYPE="vm"
          elif echo "$ISSUE_BODY" | grep -qi "Addon (tools/addon)"; then
            SCRIPT_TYPE="addon"
          elif echo "$ISSUE_BODY" | grep -qi "PVE Tool (tools/pve)"; then
            SCRIPT_TYPE="pve"
          else
            # Fallback: detect by filename pattern or default to ct
            if [[ "$TITLE" == *"-vm"* ]]; then
              SCRIPT_TYPE="vm"
            else
              SCRIPT_TYPE="ct"
            fi
          fi

          echo "SCRIPT_TYPE=$SCRIPT_TYPE" >> $GITHUB_ENV
          echo "Detected script type: $SCRIPT_TYPE for title: $TITLE"

      - name: Check if Files Exist in community-scripts/ProxmoxVED
        id: check_files
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          REPO="community-scripts/ProxmoxVED"
          API_URL="https://api.github.com/repos/$REPO/contents"
          TITLE="${{ env.TITLE }}"
          SCRIPT_TYPE="${{ env.SCRIPT_TYPE }}"

          # Define files based on script type
          case "$SCRIPT_TYPE" in
            ct)
              FILES=(
                "ct/${TITLE}.sh"
                "install/${TITLE}-install.sh"
                "frontend/public/json/${TITLE}.json"
              )
              ;;
            vm)
              FILES=(
                "vm/${TITLE}.sh"
                "frontend/public/json/${TITLE}.json"
              )
              ;;
            addon)
              FILES=(
                "tools/addon/${TITLE}.sh"
                "frontend/public/json/${TITLE}.json"
              )
              ;;
            pve)
              FILES=(
                "tools/pve/${TITLE}.sh"
              )
              ;;
          esac

          EXISTING_FILES=()

          for FILE in "${FILES[@]}"; do
            STATUS=$(curl -s -o /dev/null -w "%{http_code}" -H "Authorization: token $GH_TOKEN" "$API_URL/$FILE")
            if [ "$STATUS" -eq 200 ]; then
              EXISTING_FILES+=("$FILE")
              echo "$FILE exists in $REPO"
            else
              echo "$FILE does NOT exist in $REPO"
            fi
          done
          echo "EXISTING_FILES=${EXISTING_FILES[*]}" >> $GITHUB_ENV

      - name: Create message to send
        id: create_message
        run: |
          TITLE="${{ env.TITLE }}"
          SCRIPT_TYPE="${{ env.SCRIPT_TYPE }}"

          VAR="The ${TITLE} script is ready for testing:\n"

          # Generate correct command based on script type
          case "$SCRIPT_TYPE" in
            ct)
              VAR+="\`\`\`bash -c \"\$(curl -fsSL https://github.com/community-scripts/ProxmoxVED/raw/main/ct/${TITLE}.sh)\"\`\`\`\n"
              ;;
            vm)
              VAR+="\`\`\`bash -c \"\$(curl -fsSL https://github.com/community-scripts/ProxmoxVED/raw/main/vm/${TITLE}.sh)\"\`\`\`\n"
              ;;
            addon)
              VAR+="\`\`\`bash -c \"\$(curl -fsSL https://github.com/community-scripts/ProxmoxVED/raw/main/tools/addon/${TITLE}.sh)\"\`\`\`\n"
              ;;
            pve)
              VAR+="\`\`\`bash -c \"\$(curl -fsSL https://github.com/community-scripts/ProxmoxVED/raw/main/tools/pve/${TITLE}.sh)\"\`\`\`\n"
              ;;
          esac

          # Try to get JSON info (may not exist for all types)
          JSON_FILE=""
          case "$SCRIPT_TYPE" in
            ct|vm|addon)
              JSON_FILE="frontend/public/json/${TITLE}.json"
              ;;
          esac

          if [[ -n "$JSON_FILE" ]]; then
            JSON=$(curl -fsSL "https://github.com/community-scripts/ProxmoxVED/raw/main/${JSON_FILE}" 2>/dev/null || echo "{}")

            if [[ "$JSON" != "{}" && "$JSON" != "" ]]; then
              username=$(echo "$JSON" | jq -r '.default_credentials.username // empty')
              password=$(echo "$JSON" | jq -r '.default_credentials.password // empty')

              if [[ -n "$username" || -n "$password" ]]; then
                VAR+="Default credentials:\n"
                [[ -n "$username" ]] && VAR+="Username: $username\n"
                [[ -n "$password" ]] && VAR+="Password: $password\n"
                VAR+="\n"
              fi

              # Get notes
              mapfile -t notes_array < <(echo "$JSON" | jq -r '.notes[]?.text // empty' 2>/dev/null)
              if [ ${#notes_array[@]} -gt 0 ]; then
                for note in "${notes_array[@]}"; do
                  [[ -n "$note" ]] && VAR+="$note\n"
                done
                VAR+="\n"
              fi
            fi
          fi

          VAR+="Note: This is not in the official repo yet—it's just a dev version! After merging into ProxmoxVE, it will need to be recreated.\n\n"
          VAR+="Discussion & issue tracking:\n"
          VAR+="${{ github.event.issue.html_url }}"
          echo "message=$VAR" >> $GITHUB_ENV

      - name: Check if Discord thread exists
        id: check_thread
        run: |
          ISSUE_TITLE="${{ github.event.issue.title }}"

          THREAD_ID=$(curl -s -X GET "https://discord.com/api/v10/guilds/${{ secrets.DISCORD_GUILD_ID }}/threads/active" \
          -H "Authorization: Bot ${{ secrets.DISCORD_BOT_TOKEN }}" \
          -H "Content-Type: application/json" | \
          jq -r --arg TITLE "$ISSUE_TITLE" --arg PARENT_ID "${{ secrets.DISCORD_CHANNEL_ID }}" \
          '.threads[] | select(.parent_id == $PARENT_ID and .name == ("Wanted Tester for " + $TITLE)) | .id')

          if [ -n "$THREAD_ID" ]; then
            echo "thread_exists=true" >> "$GITHUB_OUTPUT"
          else
            echo "thread_exists=false" >> "$GITHUB_OUTPUT"
          fi

      - name: Create a forumpost in Discord
        if: steps.check_thread.outputs.thread_exists != 'true'
        id: post_to_discord
        env:
          DISCORD_CHANNEL_ID: ${{ secrets.DISCORD_CHANNEL_ID }}
          DISCORD_BOT_TOKEN: ${{ secrets.DISCORD_BOT_TOKEN }}
          TITLE: ${{ github.event.issue.title }}
          MESSAGE: ${{ env.message }}
        run: |
          JSON_PAYLOAD=$(jq -n --arg name "Wanted Tester for $TITLE" --arg content "$MESSAGE" '{name: $name, message: {content: $content | gsub("\\\\n"; "\n")}, applied_tags: []}')
          echo "JSON Payload: $JSON_PAYLOAD"

          RESPONSE=$(curl -s -w "\n%{http_code}" -X POST "https://discord.com/api/v10/channels/$DISCORD_CHANNEL_ID/threads" \
            -H "Authorization: Bot $DISCORD_BOT_TOKEN" \
            -H "Content-Type: application/json" \
            -d "$JSON_PAYLOAD")

          HTTP_BODY=$(echo "$RESPONSE" | head -n -1)
          HTTP_CODE=$(echo "$RESPONSE" | tail -n1)
          THREAD_ID=$(echo "$HTTP_BODY" | jq -r '.id')

          STATUS_CODE=$(echo "$RESPONSE" | tail -n 1)
          if [[ "$HTTP_CODE" == "201" && -n "$THREAD_ID" ]]; then
            LOCK_RESPONSE=$(curl -s -X PATCH "https://discord.com/api/v10/channels/$THREAD_ID" \
              -H "Authorization: Bot $DISCORD_BOT_TOKEN" \
              -H "Content-Type: application/json" \
              -d '{"locked": true}')
            echo "Discord post created successfully!"
          else
            echo "Response: $RESPONSE"
            echo "Failed to create Discord post! Status code: $STATUS_CODE"
            exit 1
          fi

      - name: Comment on Issue
        if: steps.check_thread.outputs.thread_exists != 'true'
        id: comment_on_issue
        env:
          MESSAGE: ${{ env.message }}
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          echo -e "$MESSAGE" > comment.txt
          sed -i '/Discussion & issue tracking:/,$d' comment.txt
          gh issue comment ${{ github.event.issue.number }} --repo ${{ github.repository }} --body-file comment.txt
