# CDP Edge - Setup CI/CD e Versionamento Automático

## Fluxo Escolhido

Escolha **UMA** das opções:

| Opção | Versão | Quando usar |
|-------|--------|------------|
| **semantic-release** | Automática | Commits convencionais, time pequeno |
| **Manual workflow** | Controlada | Quer aprovar cada release |

---

## PASSO 1: Criar Conta e Token no npm

```bash
# 1. Criar conta em https://www.npmjs.com/signup

# 2. Login
npm login

# 3. Criar token de automação
# Vá em: https://www.npmjs.com/settings/tokens
# - Clique "Create New Token"
# - Nome: "GitHub Actions"
# - Tipo: "Automation"
# - Copie o token gerado
```

---

## PASSO 2: Configurar Secrets no GitHub

Vá no repositório: `Settings` → `Secrets and variables` → `Actions` → `New repository secret`

**Adicione:**

| Nome | Valor |
|------|-------|
| `NPM_TOKEN` | Token do passo 1 |
| `GITHUB_TOKEN` | Já existe automaticamente (não precisa criar) |

---

## PASSO 3: Configurar o Workflow

### Como funciona hoje

Dois workflows, com papéis separados:

| Workflow | Quando roda | O que faz |
|---|---|---|
| **Release** (`release.yml`, semantic-release) | a cada push no `main` | calcula a versão pelos commits, atualiza `package.json`, `package-lock.json` e `CHANGELOG.md` (commit `chore(release): X.Y.Z [skip ci]`), cria a tag e o GitHub Release. **Não publica no npm.** |
| **Publish to npm** (`publish.yml`, manual) | você dispara em `Actions` | roda build, `version:check`, `typecheck`, testes e `agents:check` e publica no npm a versão que está no `main`. Recusa se essa versão já existir no npm. |

Tipos de commit (Conventional Commits):

```bash
git commit -m "feat: add Reddit support"        # minor
git commit -m "fix: correct TikTok endpoint"     # patch
git commit -m "feat!: remove GTM support"        # major
```

### Publicar no npm

1. Faça push dos commits no `main` e espere o workflow **Release** terminar (ele sobe a versão).
2. `git pull` e confira `package.json` e a tag criada.
3. Em `Actions` → `Publish to npm` → `Run workflow`. Deixe `dry_run` marcado na primeira vez e confira a lista de arquivos.
4. Rode de novo com `dry_run` desmarcado para publicar de verdade.

Pré-requisito: o secret `NPM_TOKEN` (passo 2) e permissão de escrita do `GITHUB_TOKEN` em `contents` (Settings → Actions → General → Workflow permissions: *Read and write*), usada pelo commit de release.

> Se a branch `main` tiver proteção que bloqueie push direto, o commit de release do semantic-release será recusado. Libere o `github-actions[bot]` ou ajuste a regra.

---

## PASSO 4: Configurar Conventional Commits (Opcional mas recomendado)

```bash
# Instalar commitlint
npm install -D @commitlint/cli @commitlint/config-conventional

# Criar commitlint.config.js
echo "export default { extends: ['@commitlint/config-conventional'] };" > commitlint.config.js

# Adicionar ao package.json scripts
# "prepare": "husky install"
# "commitlint": "commitlint --edit"

# Instalar husky
npm install -D husky
npx husky install
npx husky add .husky/commit-msg 'npx --no -- commitlint --edit "$1"'
```

Agora commits inválidos são bloqueados!

---

## Fluxo Completo de Desenvolvimento

```
Desenvolvimento
      ↓
git commit -m "feat: nova funcionalidade"
      ↓
git push origin main
      ↓
GitHub Actions detecta push
      ↓
    ┌─────────┐
    │ semantic-│  (se Opção A)
    │ release  │──→ Calcula versão
    └─────────┘
      ↓
    ┌─────────┐
    │  CI/CD  │──→ Build + Test
    └─────────┘
      ↓
    ┌─────────┐
    │ Publish │──→ npm publish
    │  npm    │
    └─────────┘
      ↓
    ┌─────────┐
    │GitHub   │──→ Criar Release
    │ Release │    + Changelog
    └─────────┘
```

---

## Verificação

```bash
# Ver releases criados
npm view cdp-edge versions

# Ver changelog
# Vá em: https://github.com/seu-usuario/cdp-edge/releases
```

---

## Solução de Problemas

### Erro: "401 Unauthorized"
→ Verifique se `NPM_TOKEN` está correto no GitHub Secrets

### Erro: "403 Forbidden"
→ Verifique se o nome do pacote está disponível no npm

### Release não aparece
→ Verifique se o workflow falhou em `Actions`

---

## Dicas Avançadas

### Pre-release (beta, alpha)

```bash
git commit -m "feat: add beta feature

Release: 1.1.0-beta.1"
```

### Ignorar commits no release

```
# .releaserc.json
{
  "branches": ["main"],
  "tagFormat": "v${version}",
  "plugins": [
    "@semantic-release/commit-analyzer",
    {
      "preset": "conventionalcommits",
      "releaseRules": [
        { "type": "chore", "scope": "deps", "release": "patch" }
      ]
    }
  ]
}
```

### Multiple publish channels

Use scopes para diferentes canais:
```bash
npm publish --tag beta    # @beta
npm publish --tag next    # @next
```
