# ASDM Workspace Azure Pipelines Configuration
# This pipeline handles validation, packaging, and deployment of ASDM toolsets

trigger:
  branches:
    include:
      - main
      - develop
  paths:
    include:
      - .asdm/toolsets/*
      - .codebuddy/commands/*

pr:
  branches:
    include:
      - main
      - develop

pool:
  vmImage: 'ubuntu-latest'

variables:
  - name: WORKSPACE_DIR
    value: '.workspace'
  - name: ASDM_DIR
    value: '.asdm'
  - name: CODEBUDDY_DIR
    value: '.codebuddy'

stages:
  - stage: Validate
    displayName: 'Validate Toolsets'
    jobs:
      - job: ValidateManifests
        displayName: 'Validate Manifest Files'
        steps:
          - task: NodeTool@0
            inputs:
              versionSpec: '18.x'
            displayName: 'Install Node.js'

          - bash: |
              echo "Validating ASDM toolset manifests..."
              ERROR_COUNT=0
              for manifest in $(find .asdm/toolsets -name "manifest.json" -type f); do
                echo "Checking: $manifest"
                if ! node -e "JSON.parse(require('fs').readFileSync('$manifest','utf8'))" 2>/dev/null; then
                  echo "ERROR: Invalid JSON in $manifest"
                  ERROR_COUNT=$((ERROR_COUNT + 1))
                else
                  # Validate required fields
                  node -e "
                    const m = JSON.parse(require('fs').readFileSync('$manifest','utf8'));
                    const required = ['guid','name','version','commands'];
                    const missing = required.filter(k => !m[k]);
                    if (missing.length) {
                      console.error('Missing fields: ' + missing.join(', '));
                      process.exit(1);
                    }
                  " 2>/dev/null
                  if [ $? -ne 0 ]; then
                    echo "ERROR: Missing required fields in $manifest"
                    ERROR_COUNT=$((ERROR_COUNT + 1))
                  fi
                fi
              done
              echo "Total errors: $ERROR_COUNT"
              if [ $ERROR_COUNT -gt 0 ]; then
                echo "Validation FAILED"
                exit 1
              fi
              echo "Validation PASSED"
            displayName: 'Validate manifest.json files'

          - bash: |
              echo "Checking for orphan command references..."
              for cmd_file in $(find .codebuddy/commands -name "*.md" -type f); do
                filename=$(basename "$cmd_file" .md)
                echo "Command: $filename"
              done
            displayName: 'Check command references'

      - job: ValidateMarkdown
        displayName: 'Validate Markdown Documents'
        steps:
          - bash: |
              echo "Checking markdown files for basic validity..."
              ERROR_COUNT=0
              for md_file in $(find .asdm/toolsets -name "*.md" -type f); do
                if [ ! -s "$md_file" ]; then
                  echo "WARNING: Empty markdown file: $md_file"
                fi
              done
              echo "Markdown check complete"
            displayName: 'Validate markdown content'

  - stage: Package
    displayName: 'Package Workspace'
    dependsOn: Validate
    condition: succeeded()
    jobs:
      - job: PackageToolsets
        displayName: 'Package ASDM Toolsets'
        steps:
          - bash: |
              echo "Collecting toolset information..."
              TOOLSET_COUNT=$(find .asdm/toolsets -mindepth 1 -maxdepth 1 -type d | wc -l)
              COMMAND_COUNT=$(find .codebuddy/commands -name "*.md" -type f | wc -l)
              echo "Found $TOOLSET_COUNT toolsets"
              echo "Found $COMMAND_COUNT commands"

              # Generate toolset summary
              node -e "
                const fs = require('fs');
                const path = require('path');
                const dirs = fs.readdirSync('.asdm/toolsets');
                const summary = dirs.map(d => {
                  try {
                    const m = JSON.parse(fs.readFileSync(path.join('.asdm/toolsets', d, 'manifest.json'), 'utf8'));
                    return { name: m.name, version: m.version, guid: m.guid, commands: Object.keys(m.commands || {}) };
                  } catch(e) { return { name: d, error: e.message }; }
                });
                fs.writeFileSync('.workspace/toolset-summary.json', JSON.stringify(summary, null, 2));
                console.log('Summary written to .workspace/toolset-summary.json');
              "
            displayName: 'Generate toolset summary'

          - task: PublishBuildArtifact@1
            inputs:
              PathtoPublish: '.asdm'
              ArtifactName: 'asdm-toolsets'
              publishLocation: 'Container'
            displayName: 'Publish ASDM toolsets artifact'

          - task: PublishBuildArtifact@1
            inputs:
              PathtoPublish: '.codebuddy'
              ArtifactName: 'codebuddy-commands'
              publishLocation: 'Container'
            displayName: 'Publish CodeBuddy commands artifact'

          - task: PublishBuildArtifact@1
            inputs:
              PathtoPublish: '.workspace'
              ArtifactName: 'workspace-output'
              publishLocation: 'Container'
            displayName: 'Publish workspace output artifact'

  - stage: Deploy
    displayName: 'Deploy Toolsets'
    dependsOn: Package
    condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))
    jobs:
      - job: DeployToolsets
        displayName: 'Deploy to Target Environment'
        steps:
          - bash: |
              echo "Downloading artifacts..."
              echo "Deploying ASDM toolsets to target environment..."
              # Add deployment steps specific to your target environment
              echo "Deployment completed"
            displayName: 'Deploy toolsets'
