name: Code checks
on:
  push:
    branches:
      - main
    tags:
      - '*.*.*'
  pull_request:
    branches:
      - main

jobs:
  check-url-paths:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Check for incorrect absolute '/php/' URLs in frontend code
        run: |
          echo "🔍 Checking for incorrect absolute '/php/' URLs (should be 'php/' or './php/')..."

          MATCHES=$(grep -rE "['\"]/php/" --include=\*.{js,php,html} ./front \
            | grep -E "\.get|\.post|\.ajax|fetch|url\s*:") || true

          if [ -n "$MATCHES" ]; then
            echo "$MATCHES"
            echo "❌ Found incorrectly absolute '/php/' URLs. Use 'php/' or './php/' for relative paths."
            exit 1
          else
            echo "✅ No bad '/php/' URLs found."
          fi



      - name: Check Python syntax
        run: |
          set -e
          echo "🔍 Checking Python syntax..."
          find . -name "*.py" -print0 | xargs -0 -n1 python3 -m py_compile

  lint:
    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.11'

      - name: Install linting tools
        run: |
          # Python linting
          pip install flake8
          # Docker linting
          wget -O /tmp/hadolint https://github.com/hadolint/hadolint/releases/latest/download/hadolint-Linux-x86_64
          chmod +x /tmp/hadolint
          # PHP and shellcheck for syntax checking
          sudo apt-get update && sudo apt-get install -y php-cli shellcheck

      - name: Shell check
        continue-on-error: true
        run: |
          echo "🔍 Checking shell scripts..."
          find . -name "*.sh" -exec shellcheck {} \;

      - name: Python lint
        continue-on-error: true
        run: |
          echo "🔍 Linting Python code..."
          flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
          flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics

      - name: PHP check
        continue-on-error: true
        run: |
          echo "🔍 Checking PHP syntax..."
          find . -name "*.php" -exec php -l {} \;

      - name: Docker lint
        continue-on-error: true
        run: |
          echo "🔍 Linting Dockerfiles..."
          /tmp/hadolint --config .hadolint.yaml Dockerfile* || true

  docker-tests:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Run Docker-based tests
        run: |
          echo "🐳 Running Docker-based tests..."
          chmod +x ./test/docker_tests/run_docker_tests.sh
          ./test/docker_tests/run_docker_tests.sh
