name: Build and Push Docker Image

on:
  push:
    tags:
      - 'v*'  # Triggers on v1.0.0, v2.1.3, etc.
  workflow_dispatch:  # Manual trigger option

jobs:
  build-and-push:
    runs-on: ubuntu-latest
    permissions:
      contents: write
      packages: write

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

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

      - name: Login to GitHub Container Registry
        uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Extract version from tag
        id: meta
        run: |
          # Ensure we're building from a tag
          if [[ "$GITHUB_REF" != refs/tags/* ]]; then
            echo "Error: This workflow should only run on tag pushes"
            echo "GITHUB_REF: $GITHUB_REF"
            exit 1
          fi
          VERSION=${GITHUB_REF#refs/tags/v}
          echo "version=$VERSION" >> $GITHUB_OUTPUT
          echo "Building version: $VERSION"

          # Docker tags must be lowercase
          REPO_OWNER_LOWER=$(echo "${{ github.repository_owner }}" | tr '[:upper:]' '[:lower:]')
          echo "repo_owner_lower=$REPO_OWNER_LOWER" >> $GITHUB_OUTPUT
          echo "Repository owner (lowercase): $REPO_OWNER_LOWER"

          # Check if this is a pre-release (alpha, beta, rc)
          # Only stable releases get the 'latest' tag
          if [[ "$VERSION" == *"-alpha"* ]] || [[ "$VERSION" == *"-beta"* ]] || [[ "$VERSION" == *"-rc"* ]]; then
            echo "is_prerelease=true" >> $GITHUB_OUTPUT
            echo "This is a pre-release version - will NOT tag as 'latest'"
          else
            echo "is_prerelease=false" >> $GITHUB_OUTPUT
            echo "This is a stable release - will tag as 'latest'"
          fi

      - name: Generate Docker tags
        id: docker_tags
        run: |
          VERSION="${{ steps.meta.outputs.version }}"
          REPO_OWNER_LOWER="${{ steps.meta.outputs.repo_owner_lower }}"
          IS_PRERELEASE="${{ steps.meta.outputs.is_prerelease }}"

          # Always tag with version
          TAGS="ghcr.io/$REPO_OWNER_LOWER/ai-trader:$VERSION"

          # Only add 'latest' tag for stable releases
          if [[ "$IS_PRERELEASE" == "false" ]]; then
            TAGS="${TAGS}"$'\n'"ghcr.io/$REPO_OWNER_LOWER/ai-trader:latest"
            echo "Tagging as both $VERSION and latest"
          else
            echo "Pre-release detected - tagging as $VERSION only (NOT latest)"
          fi

          echo "tags<<EOF" >> $GITHUB_OUTPUT
          echo "$TAGS" >> $GITHUB_OUTPUT
          echo "EOF" >> $GITHUB_OUTPUT

      - name: Build and push Docker image
        uses: docker/build-push-action@v5
        with:
          context: .
          push: true
          tags: ${{ steps.docker_tags.outputs.tags }}
          cache-from: type=gha
          cache-to: type=gha,mode=max

      - name: Image published
        run: |
          echo "✅ Docker image published successfully!"
          echo "📦 Pull with: docker pull ghcr.io/${{ steps.meta.outputs.repo_owner_lower }}/ai-trader:${{ steps.meta.outputs.version }}"

          if [[ "${{ steps.meta.outputs.is_prerelease }}" == "false" ]]; then
            echo "📦 Or latest: docker pull ghcr.io/${{ steps.meta.outputs.repo_owner_lower }}/ai-trader:latest"
          else
            echo "⚠️  Pre-release version - 'latest' tag not updated"
          fi

      - name: Generate release notes
        id: release_notes
        run: |
          VERSION="${{ steps.meta.outputs.version }}"
          REPO_OWNER_LOWER="${{ steps.meta.outputs.repo_owner_lower }}"

          # Check if this is an alpha/beta/rc release
          if [[ "$VERSION" == *"-alpha"* ]] || [[ "$VERSION" == *"-beta"* ]] || [[ "$VERSION" == *"-rc"* ]]; then
            PRERELEASE="true"
            RELEASE_TYPE="Pre-release"
          else
            PRERELEASE="false"
            RELEASE_TYPE="Release"
          fi
          echo "prerelease=$PRERELEASE" >> $GITHUB_OUTPUT

          # Generate generic release notes template
          cat > /tmp/release_notes.md << 'EOF'
          ## Release Notes

          <!-- TODO: Add release summary and highlights here -->

          ### Quick Start

          **Using Docker Compose:**
          ```bash
          git clone https://github.com/Xe138/AI-Trader.git
          cd AI-Trader
          cp .env.example .env
          # Edit .env with your API keys
          docker-compose up
          ```

          **Using pre-built image:**
          ```bash
          docker pull ghcr.io/REPO_OWNER/ai-trader:VERSION
          docker run --env-file .env \
            -v $(pwd)/data:/app/data \
            -v $(pwd)/logs:/app/logs \
            ghcr.io/REPO_OWNER/ai-trader:VERSION
          ```

          ### Documentation

          - [Docker Deployment Guide](docs/DOCKER.md)
          - [Release Process](docs/RELEASING.md)
          - [Full Changelog](CHANGELOG.md)

          ### Changes

          <!-- TODO: Add changes from CHANGELOG.md here -->

          See [CHANGELOG.md](CHANGELOG.md) for detailed changes.

          ---

          **Container Registry:** `ghcr.io/REPO_OWNER/ai-trader:VERSION`
          **Docker Image:** `ghcr.io/REPO_OWNER/ai-trader:latest`
          EOF

          # Replace placeholders
          sed -i "s/REPO_OWNER/$REPO_OWNER_LOWER/g" /tmp/release_notes.md
          sed -i "s/VERSION/$VERSION/g" /tmp/release_notes.md

          cat /tmp/release_notes.md

      - name: Create GitHub Release
        uses: softprops/action-gh-release@v1
        with:
          tag_name: v${{ steps.meta.outputs.version }}
          name: v${{ steps.meta.outputs.version }}
          body_path: /tmp/release_notes.md
          draft: true
          prerelease: ${{ steps.release_notes.outputs.prerelease }}
          token: ${{ secrets.GITHUB_TOKEN }}
