from __future__ import annotations

from pathlib import Path
from textwrap import dedent,indent


def init_workflow(repo_path: str, *, publish_release: bool = True, force: bool = False) -> Path:
    """
    在目标仓库生成 .github/workflows/docpack.yml
    - publish_release=True: 生成 Release（Assets 里可直接下载 docpack.zip）
    - publish_release=False: 只上传 Actions Artifact
    """
    repo = Path(repo_path).resolve()
    if not repo.exists():
        raise FileNotFoundError(f"repo not found: {repo}")

    wf_dir = repo / ".github" / "workflows"
    wf_dir.mkdir(parents=True, exist_ok=True)

    wf_file = wf_dir / "docpack.yml"
    if wf_file.exists() and not force:
        raise FileExistsError(f"{wf_file} already exists (use --force to overwrite)")

    # permissions（只有发布 release 时才需要）
    permissions_block = ""
    if publish_release:
        permissions_block = "permissions:\n  contents: write\n\n"

    # Release step：先写成“顶格”，再统一缩进到 steps 的层级（6 个空格）
    release_step = ""
    if publish_release:
        release_step = indent(
            dedent(
                """\
                - name: Publish Release (docpack.zip)
                  uses: softprops/action-gh-release@v2
                  with:
                    tag_name: docpack-${{ github.run_number }}
                    name: DocPack ${{ github.run_number }}
                    prerelease: true
                    files: docpack.zip
                  env:
                    GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
                """
            ).rstrip(),
            "      ",
        )

    yml = (
        "name: Build DocPack\n\n"
        "on:\n"
        "  push:\n"
        '    branches: ["main"]\n'
        "  workflow_dispatch:\n\n"
        f"{permissions_block}"
        "jobs:\n"
        "  build-docpack:\n"
        "    runs-on: ubuntu-latest\n"
        "    steps:\n"
        "      - name: Checkout\n"
        "        uses: actions/checkout@v4\n\n"
        "      - name: Setup Python\n"
        "        uses: actions/setup-python@v5\n"
        "        with:\n"
        '          python-version: "3.11"\n\n'
        "      - name: Install ai-dockpack (from GitHub)\n"
        "        run: |\n"
        "          python -m pip install --upgrade pip\n"
        '          pip install --no-cache-dir --force-reinstall "git+https://github.com/Kuan-Peng/ai-dockpack.git@main"\n\n'
        "      - name: Build docpack.zip\n"
        "        run: |\n"
        "          ai-dockpack build --repo . --out docpack.zip\n\n"
        "      - name: Upload artifact\n"
        "        uses: actions/upload-artifact@v4\n"
        "        with:\n"
        "          name: docpack\n"
        "          path: docpack.zip\n"
    )

    if publish_release:
        yml = yml + "\n" + release_step + "\n"

    wf_file.write_text(yml, encoding="utf-8")
    return wf_file
