name: Build & Auto-Repair
on:
  push:
    branches: [main, develop]
  pull_request:
    branches: [main]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: "20"

      - name: Install dependencies
        run: npm ci --no-audit --no-fund

      - name: Install Playwright
        run: npx playwright install chromium firefox

      - name: Build check
        id: build
        continue-on-error: true
        run: npx tsc --noEmit

      - name: Run self-healing setup
        if: steps.build.outcome == 'failure'
        run: node scripts/setup.mjs --self-heal

      - name: Run code repair agent
        if: steps.build.outcome == 'failure'
        env:
          OLLAMA_HOST: ${{ vars.OLLAMA_HOST || 'http://localhost:11434' }}
        run: node scripts/code-repair-agent.mjs --ci

      - name: Re-check build after repair
        id: rebuild
        continue-on-error: true
        run: npx tsc --noEmit

      - name: Commit fixes
        if: steps.build.outcome == 'failure' && steps.rebuild.outcome == 'success'
        run: |
          git config user.name "CRM Repair Bot"
          git config user.email "bot@coastit.co.za"
          git add -A
          git diff --cached --quiet || git commit -m "[bot] Auto-repair build errors"
          git push

      - name: Build failed — report
        if: steps.rebuild.outcome == 'failure'
        run: |
          echo "::error::Build still failing after auto-repair. Manual intervention required."
          exit 1
