<workflow>
  <critical>The workflow execution engine is governed by: {project-root}/_bmad/core/tasks/workflow.xml</critical>
  <critical>You MUST have already loaded and processed: {installed_path}/workflow.yaml</critical>
  <critical>Communicate all responses in {communication_language}</critical>

  <step n="1" goal="환경 확인">
    <critical>🔧 GITHUB SETUP - 프로젝트에 GitHub 설정 적용</critical>

    <output>📋 **GitHub 설정 초기화**

      이 워크플로우는 프로젝트에 다음 GitHub 설정을 적용합니다:
      - GitHub Actions 워크플로우 (release-on-tag.yml)
      - Issue 템플릿 (story.md, bug.md)
      - Pull Request 템플릿

    </output>

    <action>git repository 확인: git rev-parse --git-dir</action>
    <check if="git repository NOT detected">
      <output>⚠️ Git 저장소가 감지되지 않습니다.</output>
      <ask>Git 저장소를 초기화하시겠습니까? [y/n]</ask>
      <check if="user confirms">
        <action>git init</action>
        <output>✅ Git 저장소 초기화 완료</output>
      </check>
      <check if="user cancels">
        <output>❌ GitHub 설정을 적용하려면 Git 저장소가 필요합니다.</output>
        <action>HALT</action>
      </check>
    </check>

    <action>gh CLI 확인: gh --version</action>
    <check if="gh CLI not installed">
      <output>⚠️ GitHub CLI(gh)가 설치되지 않았습니다.

        설치 방법:
        - Windows: winget install GitHub.cli
        - macOS: brew install gh
        - Linux: https://github.com/cli/cli#installation

        설치 후 `gh auth login`으로 인증해주세요.
      </output>
      <ask>gh CLI 없이 템플릿만 복사하시겠습니까? [y/n]</ask>
      <check if="user cancels">
        <action>HALT</action>
      </check>
    </check>

    <action>gh CLI 인증 확인: gh auth status</action>
    <check if="gh auth 실패">
      <output>⚠️ GitHub CLI 인증이 필요합니다.</output>
      <ask>`gh auth login`을 실행하시겠습니까? [y/n]</ask>
      <check if="user confirms">
        <action>gh auth login 안내 제공</action>
      </check>
    </check>
  </step>

  <step n="2" goal="기존 설정 확인">
    <action>기존 .github 디렉토리 확인</action>

    <check if=".github 디렉토리 존재">
      <output>📁 기존 .github 디렉토리가 발견되었습니다.

        **기존 파일:**
        {{existing_files}}
      </output>

      <ask>기존 파일을 어떻게 처리할까요?
        1. 덮어쓰기 (기존 파일 백업)
        2. 병합 (기존 파일 유지, 없는 것만 추가)
        3. 취소
      </ask>

      <check if="user chooses 1">
        <action>기존 .github 디렉토리 백업: .github.backup.{{timestamp}}</action>
        <action>{{overwrite_mode}} = true</action>
      </check>

      <check if="user chooses 2">
        <action>{{merge_mode}} = true</action>
      </check>

      <check if="user chooses 3">
        <output>❌ GitHub 설정 취소됨</output>
        <action>HALT</action>
      </check>
    </check>

    <check if=".github 디렉토리 없음">
      <output>ℹ️ 새로운 .github 디렉토리를 생성합니다.</output>
    </check>
  </step>

  <step n="3" goal="GitHub 템플릿 복사">
    <critical>📋 COPY TEMPLATES - GitHub 템플릿 파일 복사</critical>

    <action>.github/workflows 디렉토리 생성</action>
    <action>.github/ISSUE_TEMPLATE 디렉토리 생성</action>

    <!-- GitHub Actions 복사 -->
    <check if="{{overwrite_mode}} OR workflows/release-on-tag.yml 없음">
      <action>복사: {{github_templates}}/.github/workflows/release-on-tag.yml
        → {{target_github_dir}}/workflows/release-on-tag.yml</action>
      <output>✅ GitHub Actions 워크플로우 복사됨: release-on-tag.yml</output>
    </check>

    <!-- Issue 템플릿 복사 -->
    <check if="{{overwrite_mode}} OR ISSUE_TEMPLATE/story.md 없음">
      <action>복사: {{github_templates}}/.github/ISSUE_TEMPLATE/story.md
        → {{target_github_dir}}/ISSUE_TEMPLATE/story.md</action>
      <output>✅ Issue 템플릿 복사됨: story.md</output>
    </check>

    <check if="{{overwrite_mode}} OR ISSUE_TEMPLATE/bug.md 없음">
      <action>복사: {{github_templates}}/.github/ISSUE_TEMPLATE/bug.md
        → {{target_github_dir}}/ISSUE_TEMPLATE/bug.md</action>
      <output>✅ Issue 템플릿 복사됨: bug.md</output>
    </check>

    <!-- PR 템플릿 복사 -->
    <check if="{{overwrite_mode}} OR PULL_REQUEST_TEMPLATE.md 없음">
      <action>복사: {{github_templates}}/.github/PULL_REQUEST_TEMPLATE.md
        → {{target_github_dir}}/PULL_REQUEST_TEMPLATE.md</action>
      <output>✅ PR 템플릿 복사됨: PULL_REQUEST_TEMPLATE.md</output>
    </check>
  </step>

  <step n="4" goal="원격 저장소 확인">
    <action>원격 저장소 확인: git remote -v</action>

    <check if="원격 저장소 없음">
      <output>⚠️ 원격 저장소가 설정되지 않았습니다.</output>
      <ask>GitHub 저장소를 생성하시겠습니까? [y/n]</ask>

      <check if="user confirms">
        <ask>저장소 이름을 입력해주세요:</ask>
        <ask>공개(public) 또는 비공개(private)? [public/private]</ask>
        <action>gh repo create {{repo_name}} --{{visibility}} --source=. --remote=origin</action>
        <output>✅ GitHub 저장소 생성됨: {{repo_url}}</output>
      </check>
    </check>

    <check if="원격 저장소 존재">
      <action>저장소 정보 추출: {{owner}}/{{repo}}</action>
      <output>✅ 원격 저장소: {{owner}}/{{repo}}</output>
    </check>
  </step>

  <step n="5" goal="저장소 머지 규칙 설정">
    <critical>⚙️ REPO SETTINGS - 저장소 머지 규칙 설정</critical>

    <output>📋 **저장소 머지 규칙 설정**

      머지 전략을 선택해주세요:
      1. Squash + Merge Commit (권장) — Squash Merge와 Merge Commit 모두 허용
      2. Merge Commit만 — Merge Commit만 허용 (머지 기록 유지)
      3. Squash만 — Squash Merge만 허용

      모든 전략에 머지 후 브랜치 자동 삭제가 적용됩니다.
    </output>

    <ask>저장소 머지 규칙을 설정하시겠습니까? [y/n]</ask>

    <check if="user confirms">
      <ask>머지 전략을 선택해주세요: [1/2/3] (기본: 1)</ask>

      <check if="user chooses 1 (squash-and-merge)">
        <action>gh api repos/{owner}/{repo} -X PATCH -F allow_squash_merge=true -F allow_merge_commit=true -F allow_rebase_merge=false -F delete_branch_on_merge=true</action>
        <action>config.yaml에 merge_strategy 저장: _bmad/bmm/config.yaml의 merge_strategy 필드를 squash-and-merge로 업데이트</action>
        <action>CLAUDE.md 머지 명령 업데이트: CLAUDE.md에서 `gh pr merge` 명령을 찾아 `--squash` 플래그로 교체, 단계명 "Squash Merge"</action>
        <action>CLAUDE.md 머지 금지 원칙 추가: 브랜치 워크플로우 섹션 끝에 다음 텍스트가 없으면 추가 — `> **⚠️ 머지 금지 원칙:** "커밋해줘", "푸시해줘" 등의 요청은 해당 작업까지만 수행할 것. 머지는 되돌리기 어려우므로 "머지해줘"라는 명시적 요청이 있을 때만 실행한다.`</action>
        <output>✅ 저장소 머지 규칙 설정 완료:
          - Squash Merge: 허용
          - Merge Commit: 허용
          - Rebase Merge: 비활성화
          - Delete Branch on Merge: 활성화</output>
      </check>

      <check if="user chooses 2 (merge-only)">
        <action>gh api repos/{owner}/{repo} -X PATCH -F allow_merge_commit=true -F allow_squash_merge=false -F allow_rebase_merge=false -F delete_branch_on_merge=true</action>
        <action>config.yaml에 merge_strategy 저장: _bmad/bmm/config.yaml의 merge_strategy 필드를 merge-only로 업데이트</action>
        <action>CLAUDE.md 머지 명령 업데이트: CLAUDE.md에서 `gh pr merge` 명령을 찾아 `--merge` 플래그로 교체, 단계명 "Merge"</action>
        <action>CLAUDE.md 머지 금지 원칙 추가: 브랜치 워크플로우 섹션 끝에 다음 텍스트가 없으면 추가 — `> **⚠️ 머지 금지 원칙:** "커밋해줘", "푸시해줘" 등의 요청은 해당 작업까지만 수행할 것. 머지는 되돌리기 어려우므로 "머지해줘"라는 명시적 요청이 있을 때만 실행한다.`</action>
        <output>✅ 저장소 머지 규칙 설정 완료:
          - Merge Commit: 허용
          - Squash Merge: 비활성화
          - Rebase Merge: 비활성화
          - Delete Branch on Merge: 활성화</output>
      </check>

      <check if="user chooses 3 (squash-only)">
        <action>gh api repos/{owner}/{repo} -X PATCH -F allow_squash_merge=true -F allow_merge_commit=false -F allow_rebase_merge=false -F delete_branch_on_merge=true</action>
        <action>config.yaml에 merge_strategy 저장: _bmad/bmm/config.yaml의 merge_strategy 필드를 squash-only로 업데이트</action>
        <action>CLAUDE.md 머지 명령 업데이트: CLAUDE.md에서 `gh pr merge` 명령을 찾아 `--squash` 플래그로 교체, 단계명 "Squash Merge"</action>
        <action>CLAUDE.md 머지 금지 원칙 추가: 브랜치 워크플로우 섹션 끝에 다음 텍스트가 없으면 추가 — `> **⚠️ 머지 금지 원칙:** "커밋해줘", "푸시해줘" 등의 요청은 해당 작업까지만 수행할 것. 머지는 되돌리기 어려우므로 "머지해줘"라는 명시적 요청이 있을 때만 실행한다.`</action>
        <output>✅ 저장소 머지 규칙 설정 완료:
          - Squash Merge: 허용
          - Merge Commit: 비활성화
          - Rebase Merge: 비활성화
          - Delete Branch on Merge: 활성화</output>
      </check>
    </check>

    <check if="user cancels">
      <output>ℹ️ 저장소 머지 규칙 설정 건너뜀</output>
    </check>
  </step>

  <step n="6" goal="Git Hooks 설치">
    <critical>🔧 GIT HOOKS - master/main 브랜치 보호 hook 설치</critical>

    <action>_bmad/hooks/ 디렉토리 확인</action>

    <check if="_bmad/hooks/ 디렉토리 존재">
      <output>📋 **Git Hooks 설치**

        _bmad/hooks/ 에서 다음 hook을 .git/hooks/ 에 설치합니다:
        - pre-commit: master/main 브랜치 직접 커밋 차단
        - commit-msg: Conventional Commits 형식 검증
        - pre-push: master/main 직접 푸시 차단 + CHANGELOG 검증
        - post-merge: 삭제된 원격 브랜치 자동 정리
      </output>

      <ask>Git hooks를 설치하시겠습니까? [y/n]</ask>

      <check if="user confirms">
        <action>.git/hooks/ 디렉토리 생성 (없는 경우)</action>
        <action>_bmad/hooks/ 내 hook 파일(pre-commit, commit-msg, pre-push, post-merge)을 .git/hooks/ 에 복사
          - .ps1, .sh, .sample 파일은 제외
          - 기존 hook이 있고 BMad6GitHub hook이 아닌 경우 .backup으로 백업
          - 복사 시 CRLF를 LF로 변환 (bash 스크립트 호환성)
        </action>
        <action>설치된 hook 파일 목록 확인: ls -la .git/hooks/ (sample 제외)</action>
        <output>✅ Git Hooks 설치 완료!

          설치된 Hook:
          - pre-commit: master 브랜치 직접 커밋 차단
          - commit-msg: Conventional Commits 형식 검증
          - pre-push: master 브랜치 직접 푸시 차단
          - post-merge: 삭제된 원격 브랜치 자동 정리
        </output>
      </check>

      <check if="user cancels">
        <output>ℹ️ Git Hooks 설치 건너뜀

          나중에 설치하려면:
          - CLI: `npx @sleighmaster/bmad update` (hook 설치 선택)
          - 수동: `_bmad/hooks/install-hooks.ps1` 실행 (Windows)
        </output>
      </check>
    </check>

    <check if="_bmad/hooks/ 디렉토리 없음">
      <output>⚠️ _bmad/hooks/ 디렉토리가 없습니다. BMAD 설치를 먼저 진행해주세요.</output>
    </check>
  </step>

  <step n="7" goal="설정 완료 및 안내">
    <output>🎉 **GitHub 설정 완료!**

      **적용된 설정:**
      ✅ .github/workflows/release-on-tag.yml - 태그 push 시 자동 릴리즈
      ✅ .github/ISSUE_TEMPLATE/story.md - 스토리 이슈 템플릿
      ✅ .github/ISSUE_TEMPLATE/bug.md - 버그 리포트 템플릿
      ✅ .github/PULL_REQUEST_TEMPLATE.md - PR 템플릿
      ✅ 저장소 머지 규칙 - 선택한 머지 전략 적용, 브랜치 자동 삭제
      ✅ Git Hooks - master/main 브랜치 보호 (설치한 경우)
      ℹ️ .gitignore - BMAD 설치 시 자동 적용됨

      **다음 단계:**
      1. 변경사항 커밋: `git add .github && git commit -m "chore: add GitHub templates"`
      2. 원격 저장소에 Push: `git push origin main`
      3. GitHub Actions 확인: https://github.com/{{owner}}/{{repo}}/actions

      **사용 방법:**
      - 릴리즈 생성: SM 에이전트에서 `*github-release` 실행
      - 또는 태그 push: `git tag v1.0.0 && git push origin v1.0.0`
    </output>

    <ask>변경사항을 지금 커밋하고 Push하시겠습니까? [y/n]</ask>

    <check if="user confirms">
      <action>git add .github</action>
      <action>git commit -m "chore: add GitHub templates and workflows

- Add release-on-tag.yml for automatic releases
- Add issue templates (story, bug)
- Add pull request template

Generated by BMAD Method"</action>
      <action>git push origin {{current_branch}}</action>
      <output>✅ 변경사항 Push 완료!</output>
    </check>
  </step>

</workflow>
