# Based on https://github.com/actions/starter-workflows/blob/main/pages/nextjs.yml

name: Frontend CI/CD

on:
  push:
    branches: ["main"]
    paths:
      - frontend/**

  pull_request:
    branches: ["main"]
    types: [opened, synchronize, reopened, edited]
    paths:
      - frontend/**

  workflow_dispatch:

permissions:
  contents: read

concurrency:
  group: pages-${{ github.ref }}
  cancel-in-progress: false

jobs:
  test-json-files:
    runs-on: ubuntu-latest
    defaults:
      run:
        working-directory: frontend
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Setup Python
        uses: actions/setup-python@v4
        with:
          python-version: "3.x"

      - name: Test JSON files
        run: |
          python3 << 'EOF'
          import json
          import glob
          import os
          import sys

          def test_json_files():
              # Change to the correct directory
              json_dir = "public/json"
              if not os.path.exists(json_dir):
                  print(f"❌ Directory not found: {json_dir}")
                  return False
              
              # Find all JSON files
              pattern = os.path.join(json_dir, "*.json")
              json_files = glob.glob(pattern)
              
              if not json_files:
                  print(f"⚠️  No JSON files found in {json_dir}")
                  return True
              
              print(f"Testing {len(json_files)} JSON files for valid syntax...")
              
              invalid_files = []
              
              for file_path in json_files:
                  try:
                      with open(file_path, 'r', encoding='utf-8') as f:
                          json.load(f)
                      print(f"✅ Valid JSON: {file_path}")
                  except json.JSONDecodeError as e:
                      print(f"❌ Invalid JSON syntax in: {file_path}")
                      print(f"   Error: {e}")
                      invalid_files.append(file_path)
                  except Exception as e:
                      print(f"⚠️  Error reading: {file_path}")
                      print(f"   Error: {e}")
                      invalid_files.append(file_path)
              
              print("\n=== JSON Validation Summary ===")
              print(f"Total files tested: {len(json_files)}")
              print(f"Valid files: {len(json_files) - len(invalid_files)}")
              print(f"Invalid files: {len(invalid_files)}")
              
              if invalid_files:
                  print("\n❌ Found invalid JSON file(s):")
                  for file_path in invalid_files:
                      print(f"  - {file_path}")
                  return False
              else:
                  print("\n✅ All JSON files have valid syntax!")
                  return True

          if __name__ == "__main__":
              success = test_json_files()
              sys.exit(0 if success else 1)
          EOF
  
  build:
    if: github.repository == 'community-scripts/ProxmoxVE'
    needs: test-json-files
    runs-on: ubuntu-latest
    defaults:
      run:
        working-directory: frontend
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup Node
        uses: actions/setup-node@v4
        with:
          node-version: "20"
          cache: npm
          cache-dependency-path: frontend/package-lock.json

      - name: Install dependencies
        run: npm ci --prefer-offline --legacy-peer-deps

      - name: Configure Next.js for pages
        uses: actions/configure-pages@v5
        with:
          static_site_generator: next

      - name: Build with Next.js
        run: npm run build

      - name: Upload artifact
        if: github.ref == 'refs/heads/main'
        uses: actions/upload-pages-artifact@v3
        with:
          path: frontend/out

  deploy:
    runs-on: ubuntu-latest
    needs: build
    if: github.ref == 'refs/heads/main' && github.repository == 'community-scripts/ProxmoxVE'
    permissions:
      pages: write
      id-token: write
    environment:
      name: github-pages
      url: ${{ steps.deployment.outputs.page_url }}
    steps:
      - name: Deploy to GitHub Pages
        id: deployment
        uses: actions/deploy-pages@v4
