name: Deploy and Monitor Host Message

on:
  push:
    branches:
      - main
  schedule:
    - cron: '0 */3 * * *'

jobs:
  deploy:
    if: github.event_name == 'push'
    runs-on: ubuntu
    steps:
      - name: Checkout Code
        uses: actions/checkout@v3

      - name: Copy Files to Server
        uses: appleboy/scp-action@master
        with:
          host: 6.6.6.66
          username: quant
          password: ${{ secrets.DEPLOY_PASSWORD }}
          source: ".,!**/.git/**,!**/.trae/**,!**/.vscode/**,!**/logs/**,!**/__pycache__/**,!**/*.md"
          target: "~/host_message"

      - name: Setup and Start Application
        uses: appleboy/ssh-action@master
        with:
          host: 6.6.6.66
          username: quant
          password: ${{ secrets.DEPLOY_PASSWORD }}
          script: |
            cd ~/host_message
            
            # Ensure python dependencies are installed
            # Check if pip3 exists, otherwise use pip
            PIP_CMD="pip"
            if command -v pip3 &> /dev/null; then
                PIP_CMD="pip3"
            fi
            
            echo "Installing dependencies using $PIP_CMD..."
            $PIP_CMD install -r requirements.txt
            
            # Make sure start script is executable
            chmod +x start.sh
            
            # Run start script (handles start/restart)
            ./start.sh

  monitor:
    if: github.event_name == 'schedule'
    runs-on: ubuntu-22.04
    steps:
      - name: Periodic Health Check
        uses: appleboy/ssh-action@master
        with:
          host: 6.6.6.66
          username: quant
          password: ${{ secrets.DEPLOY_PASSWORD }}
          script: |
            cd ~/host_message
            
            # Run start.sh which includes health check logic
            # If app is down or unhealthy, it will restart it
            ./start.sh
