# /setup-posthog — PostHog Analytics Integration Wizard

## Usage
```
/setup-posthog              # Full setup (detect → install → validate → generate → configure KPI adapter → suggest events)
/setup-posthog provider     # Generate only PostHogProvider + pageview tracker
/setup-posthog events       # Generate only event tracking helper
/setup-posthog status       # Check integration completeness
/setup-posthog connect-kpis # Scan codebase for events, map them to KPIs
```

## Input
- `$ARGUMENTS` — optional: one of the modes above (defaults to full setup)

## Process

Parse `$ARGUMENTS` to determine mode. If empty or "setup", run the full wizard.

---

### Mode: Full Setup (default)

Runs the complete PostHog analytics integration wizard:

1. **Detect Framework**: Reads `package.json` to identify Next.js (App/Pages Router), Express, Fastify, Remix, or generic Node.js. Checks for TypeScript and `src/` directory.

2. **Install SDK**: If `posthog-js` is not in `node_modules`, runs `npm install posthog-js`. For non-Next.js frameworks, also installs `posthog-node`.

3. **Validate API Key**: Reads `NEXT_PUBLIC_POSTHOG_KEY` (Next.js) or `POSTHOG_API_KEY` (other) from `.env` or environment. Validates key format (must start with `phc_`).
   - If missing: prints instructions to add it and continues (key can be added later).
   - If invalid format: prints warning.
   - If valid: calls PostHog API to verify the key works.

4. **Generate Tracking Code**: Creates framework-appropriate files:
   - **Next.js App Router**: `PostHogProvider.tsx`, `PostHogPageview.tsx`, `posthog-events.ts`
   - **Next.js Pages Router**: `lib/posthog.ts`, `_app.tsx` integration instructions
   - **Generic (Express, etc.)**: `lib/posthog.ts` (posthog-node client)
   - **Never overwrites existing files** — skips with a warning.

5. **Update .env**: Appends PostHog key and host variables if not present. Ensures `.env` is in `.gitignore`.

6. **Configure KPI Adapter**: Adds a `posthog` adapter entry to `data/business-context.json` so the KPI dashboard can pull metrics from PostHog. Skips if already configured.

7. **Suggest Starter Events**: Recommends framework-specific events to track (e.g., `signed_up`, `feature_used`, `upgrade_clicked`, `cta_clicked`). Provides code snippets for adding them.

---

### Mode: `provider`

Generates only the PostHogProvider component and pageview tracker for the detected framework. Useful if you already have the SDK installed and key configured but need the React components.

---

### Mode: `events`

Generates only the event tracking helper file (`posthog-events.ts` or `lib/posthog.ts`). Useful for adding typed event tracking to an existing PostHog setup.

---

### Mode: `status`

Audits the current integration:
- Is PostHog SDK installed?
- Is the API key configured?
- Is the key format valid?
- Are generated files present (Provider, Pageview, events helper)?
- Is the KPI adapter configured in business-context.json?

Reports completeness as a percentage.

---

### Mode: `connect-kpis`

Scans the user's codebase for PostHog event calls and maps them to KPIs:

1. **Find Events**: Searches for `posthog.capture('...')`, `trackEvent('...')`, and `client.capture({ event: '...' })` patterns across `.ts`, `.tsx`, `.js`, `.jsx` files. Ignores `node_modules`, `dist`, and `$`-prefixed internal events.

2. **Read Existing KPIs**: Loads KPI definitions from `data/goals.json`.

3. **Generate Mappings**: Creates `kpi-{event-name}` → `event_name` field mappings.

4. **Update Adapter**: Writes the field mappings to the PostHog adapter in `data/business-context.json`. Creates the adapter if it doesn't exist.

5. **Report**: Lists detected events, existing KPIs, and suggested mappings.

---

## State File

`data/posthog.json` tracks:
```json
{
  "last_updated": "2026-01-15T...",
  "integration_status": {
    "sdk_installed": true,
    "api_key_valid": true,
    "provider_generated": true,
    "pageview_tracker": true,
    "event_helper": false
  },
  "framework": { "framework": "nextjs", "typescript": true, "appRouter": true, "srcDir": true },
  "generated_files": ["src/components/PostHogProvider.tsx", "src/components/PostHogPageview.tsx"]
}
```

## Error Handling

- Missing `NEXT_PUBLIC_POSTHOG_KEY` → prints instructions to add it to `.env`, continues setup
- Invalid key format (not `phc_...`) → prints warning, continues
- API key validation fails → prints error, continues (key can be fixed later)
- SDK install fails → returns failure with manual install instructions
- Target file already exists → skips with warning (never overwrites user code)
- Framework not detected → falls back to generic Node.js templates
- `business-context.json` missing → skips KPI adapter step with hint to run `vibebusiness init`
- No PostHog events found in codebase → reports zero and suggests running `posthog-setup` first
