name: CI

on:
  push:
    branches: [main, master]
  pull_request:
    branches: [main, master]
  workflow_dispatch:

jobs:
  check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: "3.12"
          cache: pip

      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install -r requirements.txt

      - name: Validate translation JSON
        run: |
          python - <<'PY'
          import json, pathlib, sys
          root = pathlib.Path("translations")
          errors = []
          for path in sorted(root.glob("*.json")):
              try:
                  json.loads(path.read_text(encoding="utf-8"))
                  print(f"OK {path}")
              except Exception as exc:
                  errors.append(f"{path}: {exc}")
          if errors:
              print("\n".join(errors))
              sys.exit(1)
          PY

      - name: Compile Python sources
        run: python -m compileall -q app.py telegram_bot.py managers db

      - name: Import smoke check
        env:
          DATABASE_URL: postgresql://amnezia:amnezia@127.0.0.1:5432/amnezia_panel
          SECRET_KEY: ci-smoke-secret
        run: |
          python - <<'PY'
          import ast
          from pathlib import Path
          # Syntax-only parse of entrypoints (full import needs live Postgres)
          for name in ("app.py", "telegram_bot.py"):
              ast.parse(Path(name).read_text(encoding="utf-8"), filename=name)
              print(f"parsed {name}")
          PY

  docker:
    runs-on: ubuntu-latest
    needs: check
    steps:
      - uses: actions/checkout@v4

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Build image
        uses: docker/build-push-action@v6
        with:
          context: .
          file: ./Dockerfile
          push: false
          tags: amnezia-panel:ci
          cache-from: type=gha
          cache-to: type=gha,mode=max
