name: AssayFlux Auto Run

on:
  push:
    branches:
      - main
  pull_request:
    branches:
      - main
  workflow_dispatch:

permissions:
  contents: read

concurrency:
  group: assayflux-ci-${{ github.ref }}
  cancel-in-progress: true

jobs:
  test:
    name: Test AssayFlux
    runs-on: ubuntu-latest
    timeout-minutes: 15

    steps:
      - name: Download repository
        uses: actions/checkout@v4

      - name: Install Python
        uses: actions/setup-python@v5
        with:
          python-version: "3.12"

      - name: Install AssayFlux
        run: |
          python -m pip install --upgrade pip
          python -m pip install -e ".[dev]"

      - name: Check Python syntax
        run: |
          python - <<'PY'
          from pathlib import Path

          files = sorted(
              path for path in Path(".").rglob("*.py")
              if not any(
                  part in {
                      ".git",
                      ".venv",
                      "venv",
                      "__pycache__",
                  }
                  for part in path.parts
              )
          )

          if not files:
              raise SystemExit("No Python files found.")

          for path in files:
              compile(
                  path.read_text(encoding="utf-8"),
                  str(path),
                  "exec",
              )
              print(f"PASS: {path}")

          print(f"\nChecked {len(files)} Python files.")
          PY

      - name: Run automated tests
        run: python -m pytest -q

      - name: Run AssayFlux examples
        run: |
          python - <<'PY'
          import subprocess
          import sys
          from pathlib import Path

          examples = [
              "examples/hello.af",
              "examples/variables.af",
              "examples/conditions.af",
              "examples/loops.af",
              "examples/functions.af",
              "examples/input.af",
          ]

          failed = []

          for filename in examples:
              path = Path(filename)
              print(f"\n--- Running {filename} ---")

              if not path.is_file():
                  print("FAIL: File not found")
                  failed.append(filename)
                  continue

              try:
                  result = subprocess.run(
                      [sys.executable, "-m", "assayflux", str(path)],
                      input="AssayFlux CI Tester\n",
                      capture_output=True,
                      text=True,
                      timeout=10,
                  )
              except subprocess.TimeoutExpired:
                  print("FAIL: Execution timed out")
                  failed.append(filename)
                  continue

              print(result.stdout)

              if result.stderr:
                  print("STDERR:")
                  print(result.stderr)

              if result.returncode != 0:
                  print(f"FAIL: Exit code {result.returncode}")
                  failed.append(filename)
              else:
                  print("PASS: Program executed successfully")

          if failed:
              raise SystemExit(f"Failed examples: {failed}")

          print(f"\nSUCCESS: All {len(examples)} examples executed.")
          PY

      - name: Validate documentation
        run: |
          python - <<'PY'
          from pathlib import Path

          required = [
              "ARCHITECTURE.md",
              "DICTIONARY.md",
              "EXAMPLES.md",
              "GRAMMAR.md",
              "INTEROPERABILITY_AND_WEB.md",
              "LANGUAGE_SPECIFICATION.md",
              "RELEASE_AND_GITHUB.md",
              "ROADMAP.md",
              "SPECIFICATION_STATUS.md",
          ]

          docs = Path("DOCS")

          if not docs.is_dir():
              raise SystemExit("DOCS directory is missing.")

          for filename in required:
              path = docs / filename

              if not path.is_file():
                  raise SystemExit(f"Missing: {path}")

              if not path.read_text(encoding="utf-8").strip():
                  raise SystemExit(f"Empty file: {path}")

              print(f"PASS: {path}")

          print("\nAll documentation files verified.")
          PY

      - name: Build Python package
        run: |
          python -m pip install build
          python -m build

      - name: Save package build
        uses: actions/upload-artifact@v4
        with:
          name: assayflux-python-package
          path: dist/
          if-no-files-found: error

      - name: Summarize results
        if: always()
        run: |
          echo "## AssayFlux Automation" >> "$GITHUB_STEP_SUMMARY"
          echo "" >> "$GITHUB_STEP_SUMMARY"
          echo "Review the steps above for test, example, documentation, and build results." >> "$GITHUB_STEP_SUMMARY"