# 본 워크플로는 task-2447 spec(allowed_resources)에 따라 workspace에도 배치되었습니다.
# 그러나 extension/ 디렉토리는 InsuRo repo (JonghyukJeon/InsuRo)에 있으므로,
# `paths: extension/**` 트리거는 workspace에서 발화되지 않습니다.
# 실 동작 워크플로는 InsuRo repo의 .github/workflows/extension-release.yml에 미러됩니다.
# workspace에서는 workflow_dispatch만 가능합니다.

name: Extension Release

on:
  push:
    branches: [main]
    paths:
      - "extension/**"
  workflow_dispatch:
    inputs:
      version:
        description: "수동 버전 태그 (선택, 비우면 manifest에서 추출)"
        required: false
        default: ""

permissions:
  contents: write

jobs:
  build-and-release:
    runs-on: [self-hosted, linux, anu-ci]
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Extract manifest version
        id: ver
        run: |
          set -e
          if [ -n "${{ inputs.version }}" ]; then
            VERSION="${{ inputs.version }}"
          else
            VERSION=$(python3 -c "import json; print(json.load(open('extension/manifest.json'))['version'])")
          fi
          if ! echo "$VERSION" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+$'; then
            echo "::error::Invalid version: $VERSION"
            exit 1
          fi
          echo "version=$VERSION" >> $GITHUB_OUTPUT
          echo "Extracted version: $VERSION"

      - name: Check existing release
        id: existing
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          TAG="extension-v${{ steps.ver.outputs.version }}"
          if gh release view "$TAG" >/dev/null 2>&1; then
            echo "exists=true" >> $GITHUB_OUTPUT
            echo "Release $TAG already exists"
          else
            echo "exists=false" >> $GITHUB_OUTPUT
          fi

      - name: Build extension zip
        if: steps.existing.outputs.exists == 'false'
        run: |
          set -e
          cd extension
          zip -r ../insuro-helper-${{ steps.ver.outputs.version }}.zip . \
            -x '*.DS_Store' \
            -x '__tests__/*' \
            -x 'README.md'
          cd ..
          ls -la insuro-helper-${{ steps.ver.outputs.version }}.zip

      - name: Create Release
        if: steps.existing.outputs.exists == 'false'
        uses: softprops/action-gh-release@v2
        with:
          tag_name: extension-v${{ steps.ver.outputs.version }}
          name: InsuRo Helper Extension v${{ steps.ver.outputs.version }}
          files: insuro-helper-${{ steps.ver.outputs.version }}.zip
          generate_release_notes: true
          body: |
            InsuRo Helper Chrome Extension v${{ steps.ver.outputs.version }}

            ohmymanager 보험료 데이터를 InsuRo로 자동 동기화 (인카 FA 전용)

            ## 설치
            1. zip 파일 다운로드
            2. 압축 해제
            3. chrome://extensions → 개발자 모드 → 압축 해제된 확장 프로그램 로드

      - name: Skip notice
        if: steps.existing.outputs.exists == 'true'
        run: echo "Release extension-v${{ steps.ver.outputs.version }} already exists. Skipping."
