name: TAKT PR Review

on:
  pull_request_target:
    types: [opened, synchronize, ready_for_review, reopened]

jobs:
  review:
    runs-on: ubuntu-latest
    environment: takt-review
    permissions:
      contents: read
      pull-requests: write
    steps:
      - uses: actions/checkout@v4
        with:
          ref: ${{ github.event.pull_request.head.sha }}
          repository: ${{ github.event.pull_request.head.repo.full_name }}
          fetch-depth: 0

      - name: API キー確認
        run: |
          if [ -z "$ANTHROPIC_API_KEY" ]; then
            echo "::error::ANTHROPIC_API_KEY is not set"
            exit 1
          fi
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}

      - uses: actions/setup-node@v4
        with:
          node-version: 20

      - name: Claude Code & TAKT インストール
        run: |
          npm install -g @anthropic-ai/claude-code
          npm install -g takt

      - name: TAKT Review 実行
        run: takt --pipeline --skip-git -i ${{ github.event.pull_request.number }} -w review
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          GH_REPO: ${{ github.repository }}

      - name: レビュー結果をPRコメントに投稿
        if: always()
        run: |
          REPORT_DIR=$(ls -td .takt/runs/*/reports 2>/dev/null | head -1)
          if [ -n "$REPORT_DIR" ]; then
            SUMMARY=$(find "$REPORT_DIR" -name "*review-summary*" -type f | head -1)
            if [ -n "$SUMMARY" ]; then
              gh pr comment ${{ github.event.pull_request.number }} --body-file "$SUMMARY"
            else
              echo "レビューサマリーが見つかりません"
            fi
          else
            echo "レポートディレクトリが見つかりません"
          fi
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          GH_REPO: ${{ github.repository }}

      - name: レビューレポートをアーティファクトに保存
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: takt-review-reports
          path: .takt/runs/*/reports/
          if-no-files-found: ignore
