name: Build and Push Docker Image

on:
  push:
    branches:
      - main

jobs:
  build-and-push:
    runs-on: ubuntu-latest # Убедитесь, что у вашего раннера есть этот тег
    
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 2

      - name: Get versions and check change
        id: version_check
        run: |
          # Извлекаем текущую версию
          CUR=$(cat VERSION | tr -d '[:space:]')
          echo "current=$CUR" >> $GITHUB_OUTPUT

          # Извлекаем сообщение последнего коммита
          COMMIT_MSG=$(git log -1 --pretty=%B | head -1)
          echo "commit_message=$COMMIT_MSG" >> $GITHUB_OUTPUT

          # Безопасно извлекаем старую версию
          PREV=$(git show HEAD~1:VERSION 2>/dev/null | tr -d '[:space:]' || echo "none")

          if [ "$CUR" != "$PREV" ]; then
            echo "changed=true" >> $GITHUB_OUTPUT
          else
            echo "changed=false" >> $GITHUB_OUTPUT
          fi

      - name: Patch DNS for Local Network
        run: |
          # Записываем IP Synology прямо в контейнер сборки
          echo "192.168.50.55 dungeonsiege.synology.me" | sudo tee -a /etc/hosts

      - name: Build Docker Image
        id: build
        run: |
          REGISTRY="dungeonsiege.synology.me/poignatov/play-life"
          VER="${{ steps.version_check.outputs.current }}"
          
          echo "Building Docker image..."
          echo "Registry: $REGISTRY"
          echo "Tag: latest"
          
          # Собираем образ
          docker build -t $REGISTRY:latest .
          
          echo "✅ Successfully built image: $REGISTRY:latest"

      - name: Log in to Gitea Registry
        if: steps.version_check.outputs.changed == 'true'
        run: |
          echo "${{ secrets.GIT_TOKEN }}" | docker login dungeonsiege.synology.me -u ${{ secrets.GIT_USERNAME }} --password-stdin

      - name: Push Docker Image
        id: push
        if: steps.version_check.outputs.changed == 'true'
        run: |
          REGISTRY="dungeonsiege.synology.me/poignatov/play-life"
          VER="${{ steps.version_check.outputs.current }}"
          
          # Тегируем образ версией
          docker tag $REGISTRY:latest $REGISTRY:$VER
          
          # Пушим оба тега
          echo "Pushing image to registry..."
          docker push $REGISTRY:latest
          docker push $REGISTRY:$VER
          
          echo "✅ Successfully pushed to registry:"
          echo "   - $REGISTRY:latest"
          echo "   - $REGISTRY:$VER"

      - name: Send Telegram notification (build success)
        if: success() && steps.version_check.outputs.changed == 'false'
        uses: appleboy/telegram-action@master
        with:
          to: ${{ secrets.TELEGRAM_TO }}
          token: ${{ secrets.TELEGRAM_TOKEN }}
          format: markdown
          message: |
            *play-life*
            `${{ steps.version_check.outputs.commit_message }}`

            Build: ✅ 
            Registration: ⏭️
            Deploy: ⏭️

      - name: Deploy to Production Server
        id: deploy
        if: steps.version_check.outputs.changed == 'true'
        uses: appleboy/ssh-action@master
        with:
          host: ${{ secrets.DEPLOY_HOST }}
          username: ${{ secrets.DEPLOY_USER }}
          password: ${{ secrets.DEPLOY_PASSWORD }}
          script: |
            set -e
            
            # Расширяем PATH для Synology (при SSH сессии PATH минимальный)
            export PATH="/usr/local/bin:/usr/syno/bin:$PATH"
            
            REGISTRY="dungeonsiege.synology.me/poignatov/play-life"
            DEPLOY_PATH="/volume1/docker/play-life"
            
            echo "🚀 Начинаю деплой на production сервер..."
            echo "PATH: $PATH"
            
            # Проверяем наличие docker
            if ! command -v docker >/dev/null 2>&1; then
              echo "❌ Docker не найден в PATH!"
              echo "Пробуем найти docker..."
              which docker || find /usr -name "docker" -type f 2>/dev/null | head -5
              exit 1
            fi
            
            DOCKER_CMD="docker"
            
            # Определяем docker-compose (может быть docker compose или docker-compose)
            if command -v docker-compose >/dev/null 2>&1; then
              DOCKER_COMPOSE_CMD="docker-compose"
            elif docker compose version >/dev/null 2>&1; then
              DOCKER_COMPOSE_CMD="docker compose"
            else
              echo "❌ Docker Compose не найден!"
              exit 1
            fi
            
            echo "Используем: $DOCKER_CMD и $DOCKER_COMPOSE_CMD"
            
            # Переходим в директорию проекта
            cd $DEPLOY_PATH
            
            # Логинимся в registry
            echo "${{ secrets.GIT_TOKEN }}" | $DOCKER_CMD login dungeonsiege.synology.me -u ${{ secrets.GIT_USERNAME }} --password-stdin
            
            # Обновляем образ
            echo "📥 Обновляю образ из registry..."
            $DOCKER_CMD pull $REGISTRY:latest
            
            # Перезапускаем контейнеры
            echo "🔄 Перезапускаю контейнеры..."
            $DOCKER_COMPOSE_CMD -f docker-compose.prod.yml up -d --force-recreate
            
            # Проверяем статус
            echo "✅ Деплой завершен успешно"
            $DOCKER_COMPOSE_CMD -f docker-compose.prod.yml ps

      - name: Send Telegram notification (publish success)
        if: steps.build.outcome == 'success' && steps.version_check.outputs.changed == 'true' && steps.push.outcome == 'success' && steps.deploy.outcome == 'success'
        uses: appleboy/telegram-action@master
        with:
          to: ${{ secrets.TELEGRAM_TO }}
          token: ${{ secrets.TELEGRAM_TOKEN }}
          format: markdown
          message: |
            *play-life*
            `${{ steps.version_check.outputs.commit_message }}`

            Build: ✅ 
            Registration: ✅
            Deploy: ✅

      - name: Send Telegram notification (push failure)
        if: steps.build.outcome == 'success' && steps.version_check.outputs.changed == 'true' && steps.push.outcome == 'failure'
        uses: appleboy/telegram-action@master
        with:
          to: ${{ secrets.TELEGRAM_TO }}
          token: ${{ secrets.TELEGRAM_TOKEN }}
          format: markdown
          message: |
            *play-life*
            `${{ steps.version_check.outputs.commit_message }}`

            Build: ✅ 
            Registration: ❌
            Deploy: ⏭️

      - name: Send Telegram notification (deploy failure)
        if: steps.build.outcome == 'success' && steps.push.outcome == 'success' && steps.version_check.outputs.changed == 'true' && steps.deploy.outcome == 'failure'
        uses: appleboy/telegram-action@master
        with:
          to: ${{ secrets.TELEGRAM_TO }}
          token: ${{ secrets.TELEGRAM_TOKEN }}
          format: markdown
          message: |
            *play-life*
            `${{ steps.version_check.outputs.commit_message }}`

            Build: ✅ 
            Registration: ✅
            Deploy: ❌

      - name: Send Telegram notification (build failure)
        if: steps.build.outcome == 'failure'
        uses: appleboy/telegram-action@master
        with:
          to: ${{ secrets.TELEGRAM_TO }}
          token: ${{ secrets.TELEGRAM_TOKEN }}
          format: markdown
          message: |
            *play-life*
            `${{ steps.version_check.outputs.commit_message }}`

            Build: ❌ 
            Registration: ⏭️
            Deploy: ⏭️