name: Build and Deploy

on:
  push:
    branches:
      - master

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.10'

      - name: Set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'

      - name: Install dependencies and Build
        run: |
          npm ci
          # Генерируем локализации перед билдом
          python scripts/manage_locales.py split
          npm run build

      - name: Deploy to Server
        uses: appleboy/scp-action@master
        with:
          host: ${{ secrets.REMOTE_HOST }}
          username: ${{ secrets.REMOTE_USER }}
          key: ${{ secrets.SSH_PRIVATE_KEY }}
          source: "dist/,backend/,nginx.conf,radionica-backend.service"
          target: "/tmp/radionica3d_deploy"
          strip_components: 0

      - name: Execute remote commands
        uses: appleboy/ssh-action@master
        with:
          host: ${{ secrets.REMOTE_HOST }}
          username: ${{ secrets.REMOTE_USER }}
          key: ${{ secrets.SSH_PRIVATE_KEY }}
          script: |
            export REMOTE_DIR="/var/www/radionica3d"
            export CHOWN_USER="www-data"
            
            # Подготовка папок
            sudo mkdir -p $REMOTE_DIR/html $REMOTE_DIR/backend
            
            # Обновление файлов
            sudo cp -r /tmp/radionica3d_deploy/dist/* $REMOTE_DIR/html/
            sudo cp -r /tmp/radionica3d_deploy/backend/* $REMOTE_DIR/backend/
            
            # Настройка бэкенда
            cd $REMOTE_DIR/backend
            [ -d venv ] || python3 -m venv venv
            source venv/bin/activate
            # Умная установка библиотек
            (cmp -s /tmp/radionica3d_deploy/backend/requirements.txt requirements.txt || (cp /tmp/radionica3d_deploy/backend/requirements.txt requirements.txt && pip install -r requirements.txt && pip install gunicorn uvicorn))
            
            # Конфиги
            sudo cp /tmp/radionica3d_deploy/nginx.conf /etc/nginx/sites-available/radionica3d
            sudo ln -sf /etc/nginx/sites-available/radionica3d /etc/nginx/sites-enabled/
            sudo nginx -t && sudo systemctl restart nginx
            
            # Служба
            sudo cp /tmp/radionica3d_deploy/radionica-backend.service /etc/systemd/system/
            sudo systemctl daemon-reload
            sudo systemctl restart radionica-backend
            
            # Права
            sudo chown -R $CHOWN_USER:$CHOWN_USER $REMOTE_DIR
            
            # Очистка
            sudo rm -rf /tmp/radionica3d_deploy
