# GitHub Action Template: Automated Version Check and Update for ioBroker Copilot Instructions
# Version: 0.4.0
# 
# This action automatically checks for template updates and creates issues when updates are available
# Copy this to your repository as .github/workflows/check-copilot-template.yml

name: Check ioBroker Copilot Template Version

on:
  schedule:
    - cron: '23 3 * * 0'  # Weekly check optimized for off-peak hours (3:23 AM UTC Sunday)
  workflow_dispatch:  # Allow manual triggering

jobs:
  check-template:
    runs-on: ubuntu-latest
    permissions:
      issues: write
      contents: read
    
    steps:
      - name: Checkout repository
        uses: actions/checkout@v6
        
      - name: Dynamic template version check
        id: version-check
        run: |
          echo "🔍 Starting dynamic ioBroker Copilot template version check..."
          
          # Get current version from local copilot instructions
          if [ -f ".github/copilot-instructions.md" ]; then
            CURRENT_VERSION=$(awk '/Version:|Template Version:/ {match($0, /([0-9]+(\.[0-9]+)*)/, arr); if (arr[1] != "") print arr[1]}' .github/copilot-instructions.md | head -1)
            if [ -z "$CURRENT_VERSION" ]; then CURRENT_VERSION="unknown"; fi
            echo "📋 Current local version: $CURRENT_VERSION"
          else
            CURRENT_VERSION="none"
            echo "❌ No .github/copilot-instructions.md file found"
          fi
          
          # Get latest version from centralized metadata
          echo "🌐 Fetching latest template version from centralized config..."
          LATEST_VERSION=$(curl -s https://raw.githubusercontent.com/DrozmotiX/ioBroker-Copilot-Instructions/main/config/metadata.json | jq -r '.version' 2>/dev/null || echo "unknown")
          if [ -z "$LATEST_VERSION" ] || [ "$LATEST_VERSION" = "null" ]; then
            LATEST_VERSION="unknown"
          fi
          echo "📋 Latest available version: $LATEST_VERSION"
          
          # Determine repository status
          COPILOT_INITIALIZED="false"
          UPDATE_NEEDED="false"
          SETUP_NEEDED="false"
          
          if [ "$CURRENT_VERSION" = "none" ]; then
            SETUP_NEEDED="true"
            echo "🆕 Status: Setup needed - no copilot instructions found"
          elif [ "$CURRENT_VERSION" = "unknown" ] || [ "$LATEST_VERSION" = "unknown" ]; then
            echo "❓ Status: Cannot determine versions - manual check required"
          else
            # Compare versions (simple string comparison for now)
            if [ "$CURRENT_VERSION" != "$LATEST_VERSION" ]; then
              UPDATE_NEEDED="true"
              COPILOT_INITIALIZED="true"
              echo "📈 Status: Update needed - $CURRENT_VERSION → $LATEST_VERSION"
            else
              COPILOT_INITIALIZED="true"
              echo "✅ Status: Up to date - version $CURRENT_VERSION"
            fi
          fi
          
          # Set outputs for later steps
          echo "current_version=$CURRENT_VERSION" >> $GITHUB_OUTPUT
          echo "latest_version=$LATEST_VERSION" >> $GITHUB_OUTPUT
          echo "copilot_initialized=$COPILOT_INITIALIZED" >> $GITHUB_OUTPUT
          echo "update_needed=$UPDATE_NEEDED" >> $GITHUB_OUTPUT
          echo "setup_needed=$SETUP_NEEDED" >> $GITHUB_OUTPUT
          
      - name: Check for existing issues
        id: issue-check
        uses: actions/github-script@v8
        with:
          script: |
            const { data: issues } = await github.rest.issues.listForRepo({
              owner: context.repo.owner,
              repo: context.repo.repo,
              state: 'open',
              labels: 'copilot-setup,automation'
            });
            
            const setupIssues = issues.filter(issue => 
              issue.title.includes('Setup ioBroker') || 
              issue.title.includes('Update ioBroker') ||
              issue.title.includes('Copilot')
            );
            
            core.setOutput('has_existing_issue', setupIssues.length > 0);
            core.setOutput('existing_count', setupIssues.length);
            
            if (setupIssues.length > 0) {
              console.log(`Found ${setupIssues.length} existing copilot setup/update issue(s)`);
            }
            
      - name: Create initial setup issue
        if: steps.version-check.outputs.setup_needed == 'true' && steps.issue-check.outputs.has_existing_issue == 'false'
        uses: actions/github-script@v8
        with:
          script: |
            const title = '🤖 Setup ioBroker GitHub Copilot Instructions';
            const body = `# Automated ioBroker Copilot Instructions Setup

            **GitHub Copilot**: Please help me set up GitHub Copilot instructions for my ioBroker adapter repository with full automation and validation.

            ## 🚨 Important Notice - Ignore GitHub Copilot's Own Setup Suggestions

            **GitHub Copilot**: If you see suggestions from GitHub Copilot about setting up copilot instructions (like creating \`.github/copilot-instructions.md\` through GitHub's interface), **IGNORE THEM**. This issue handles the complete setup process with ioBroker-specific optimizations.

            ## Setup Process

            This repository needs initial setup of GitHub Copilot instructions. Please:

            1. **Initialize with Adapter-Specific Context**: Create \`.github/copilot-instructions.md\` with basic ioBroker adapter context
            2. **Enhance with Full Template**: Merge with comprehensive template from https://raw.githubusercontent.com/DrozmotiX/ioBroker-Copilot-Instructions/main/template.md
            3. **Customize Sections**: Populate [CUSTOMIZE] sections with adapter-specific content only

            **Template Version**: ${{ steps.version-check.outputs.latest_version }}
            **Detected Status**: No copilot instructions found

            ## Reference Templates

            - **Initial Setup Action**: https://raw.githubusercontent.com/DrozmotiX/ioBroker-Copilot-Instructions/main/templates/ghAction-InitialSetup.yml
            - **Full Template**: https://raw.githubusercontent.com/DrozmotiX/ioBroker-Copilot-Instructions/main/template.md
            - **Version Check Action**: https://raw.githubusercontent.com/DrozmotiX/ioBroker-Copilot-Instructions/main/templates/ghAction-AutomatedVersionCheckAndUpdate.yml`;

            await github.rest.issues.create({
              owner: context.repo.owner,
              repo: context.repo.repo,
              title: title,
              body: body,
              labels: ['copilot-setup', 'automation']
            });
            
      - name: Create update issue  
        if: steps.version-check.outputs.update_needed == 'true' && steps.issue-check.outputs.has_existing_issue == 'false'
        uses: actions/github-script@v8
        with:
          script: |
            const title = '🤖 Update ioBroker Copilot Instructions Template';
            const body = `# Automated ioBroker Copilot Template Update Request

            **GitHub Copilot**: Please help me validate and update my ioBroker adapter's Copilot instructions template while preserving all custom sections.

            ## Update Required

            - **Current Version**: ${{ steps.version-check.outputs.current_version }}
            - **Latest Version**: ${{ steps.version-check.outputs.latest_version }}
            - **Status**: Update needed

            ## Update Process

            Please merge the latest ioBroker template while preserving all customizations:

            \`\`\`
            Merge the ioBroker template from https://raw.githubusercontent.com/DrozmotiX/ioBroker-Copilot-Instructions/main/template.md with my existing .github/copilot-instructions.md.

            CRITICAL REQUIREMENTS:
            1. Preserve ALL [CUSTOMIZE] sections and their content exactly as they are
            2. Maintain any project-specific context not already covered in the template
            3. Add the latest ioBroker best practices from the new template
            4. Update the version number to ${{ steps.version-check.outputs.latest_version }}
            5. Keep the Template Source reference up-to-date
            6. Ensure no custom content is lost during the merge
            7. REMOVE any duplicate content from [CUSTOMIZE] sections that already exists in the standard template
            \`\`\`

            ## Reference Templates

            - **Latest Template**: https://raw.githubusercontent.com/DrozmotiX/ioBroker-Copilot-Instructions/main/template.md
            - **Update Template**: https://raw.githubusercontent.com/DrozmotiX/ioBroker-Copilot-Instructions/main/templates/automated-template-update.md
            - **Version Check Action**: https://raw.githubusercontent.com/DrozmotiX/ioBroker-Copilot-Instructions/main/templates/ghAction-AutomatedVersionCheckAndUpdate.yml`;

            await github.rest.issues.create({
              owner: context.repo.owner,
              repo: context.repo.repo,
              title: title,
              body: body,
              labels: ['template-update', 'automation']
            });
            
      - name: Summary
        run: |
          echo "🎯 Template Version Check Complete"
          echo "   Current: ${{ steps.version-check.outputs.current_version }}"
          echo "   Latest: ${{ steps.version-check.outputs.latest_version }}" 
          echo "   Setup needed: ${{ steps.version-check.outputs.setup_needed }}"
          echo "   Update needed: ${{ steps.version-check.outputs.update_needed }}"
          echo "   Existing issues: ${{ steps.issue-check.outputs.existing_count }}"