/**
 * Renders `~/.claude/skills/llm-inspector-onboard/SKILL.md` for the
 * `llm-inspector onboard` subcommand. The body is a 7-phase teaching
 * workflow with `EXPLAIN / DO / PAUSE` markers — Claude reads it and walks
 * the user through real actions (start the proxy, hit /api/health, post a
 * test request, poll /api/logs) instead of just printing a static tutorial.
 *
 * The template embeds platform-aware shell snippets inline (bash + PowerShell
 * side-by-side). Skills are pure Markdown — they can't `require()` from the
 * package at runtime, so the duplication is the price of portability.
 */

export type SkillOnboardContext = {
  /** Package version (from `package.json`), stamped into the frontmatter. */
  readonly version: string;
  /** The default proxy port (mirrors `DEFAULT_PORT` in `src/cli.ts`). */
  readonly port: number;
  /**
   * One-line "detected tools" summary written into the Preflight phase so the
   * skill's instructions match the user's actual environment. Empty string
   * means "no known tool detected — fall through to the curl example".
   */
  readonly detectedSummary: string;
};

/** The 8 phase headings the spec requires. The validator checks for these. */
export const REQUIRED_PHASE_HEADINGS = [
  "Preflight",
  "Phase 1: Welcome",
  "Phase 2: Provider setup",
  "Phase 3: Start proxy",
  "Phase 4: Wire tool",
  "Phase 4.5: Wire MCP server",
  "Phase 5: First capture",
  "Phase 6: Tour & wrap",
] as const;

export function renderSkillOnboard(ctx: SkillOnboardContext): string {
  const { version, port, detectedSummary } = ctx;
  return `---
name: llm-inspector-onboard
description: Guided setup for llm-inspector v${version} — start the proxy, wire your AI coding tool, capture your first request, and learn the Web UI.
metadata:
  author: llm-inspector
  version: ${version}
---

# llm-inspector onboard

Guide the user from "I just installed llm-inspector" to "I can see my AI tool's traffic in the Web UI". This is a teaching experience — you'll do real work in their environment while explaining each step.

Environment detected by the installer:
${detectedSummary || "  (no known AI tool detected — the user can still use the generic curl example in Phase 4)"}

Default proxy port: \`${port}\` (override with \`PORT=<n> llm-inspector\` or \`--port <n>\`).

---

## Preflight

Before starting, verify the environment.

**EXPLAIN:** "Let's make sure everything we need is in place. Two quick checks."

**DO:** Run the platform-appropriate commands below. The user can copy-paste, or you can run them yourself if you have shell access.

\`\`\`bash
# Unix / macOS / WSL
node --version                  # expect >= 18
test -d "$HOME/.claude" && echo "claude-code: present" || echo "claude-code: not detected"
\`\`\`

\`\`\`powershell
# Windows PowerShell
node --version                  # expect >= 18
if (Test-Path "$env:USERPROFILE\\.claude") { Write-Host "claude-code: present" } else { Write-Host "claude-code: not detected" }
\`\`\`

**PAUSE** — if Node is older than 18, ask the user to install a newer version (https://nodejs.org) before continuing.

---

## Phase 1: Welcome

**EXPLAIN:**

\`\`\`
## Welcome to llm-inspector!

llm-inspector is a transparent HTTP proxy + Web UI for AI coding tools. Point your tool at it, and you'll see every request and response — system prompts, tool definitions, message history, SSE streaming chunks, and token counts — captured live in a browser tab.

**What we'll do in the next ~10 minutes:**
1. Add your first LLM provider (Anthropic or OpenAI key)
2. Start the proxy
3. Wire your AI tool to use it
4. Capture a first request end-to-end
5. Tour the key UI affordances

Ready? Let's start with the provider.
\`\`\`

**PAUSE** — wait for the user to confirm.

---

## Phase 2: Provider setup

**EXPLAIN:** "A 'provider' is an upstream LLM endpoint — Anthropic, OpenAI, MiniMax, etc. llm-inspector routes each request to the right upstream based on the model name. You need at least one provider configured for the proxy to forward traffic."

**DO:** Open (or create) \`~/.llm-inspector/config.json\` in the user's editor. If the file doesn't exist, create it with the structure below. Walk the user through filling in their API key for their provider of choice.

\`\`\`json
{
  "providers": [
    {
      "id": "anthropic",
      "type": "anthropic",
      "apiKey": "sk-ant-...",
      "baseUrl": "https://api.anthropic.com"
    }
  ]
}
\`\`\`

Alternative (avoid touching the config file): point the user at the Web UI → top-right Settings button → Providers tab, which has a form-driven flow.

**PAUSE** — wait for the user to confirm they have at least one provider with a key.

---

## Phase 3: Start proxy

**EXPLAIN:** "Time to start the proxy. It binds to port ${port} by default, kills any process already on that port, and prints the URL."

**DO:** Start the proxy in the background so you can keep working.

\`\`\`bash
# Unix / macOS / WSL
nohup llm-inspector --no-open > /tmp/llm-inspector.log 2>&1 &
\`\`\`

\`\`\`powershell
# Windows PowerShell
Start-Process -FilePath "llm-inspector" -ArgumentList "--no-open" -RedirectStandardOutput "$env:TEMP\\llm-inspector.log" -RedirectStandardError "$env:TEMP\\llm-inspector.err.log" -WindowStyle Hidden
\`\`\`

Then wait for the port to be ready:

\`\`\`bash
# Wait up to 10s for the port to come up
for i in $(seq 1 20); do
  curl -fsS "http://localhost:${port}/api/health" >/dev/null 2>&1 && echo "ready" && break
  sleep 0.5
done
\`\`\`

**DO:** Hit the health endpoint to confirm the proxy is alive:

\`\`\`bash
curl -sS "http://localhost:${port}/api/health"
\`\`\`

**PAUSE** — if the health check fails, show the user the log file (\`/tmp/llm-inspector.log\` or \`%TEMP%\\\\llm-inspector.log\`) and diagnose. Common issues: another process on the port, firewall, missing providers.

---

## Phase 4: Wire tool

**EXPLAIN:** "Now we tell your AI tool to send traffic through the proxy instead of directly to the upstream API. The exact env var depends on which tool you have."

**DO:** Based on the \`Environment detected\` block at the top of this skill, print the matching wiring command. Examples for each supported tool:

\`\`\`bash
# Claude Code
export ANTHROPIC_BASE_URL=http://localhost:${port}/proxy
claude

# OpenCode
export LLM_BASE_URL=http://localhost:${port}/proxy
opencode

# MiMo Code
export OPENAI_BASE_URL=http://localhost:${port}/proxy
mimo

# Cursor / Cody — set the OpenAI base URL in each tool's settings panel to http://localhost:${port}/proxy
\`\`\`

For a tool that wasn't auto-detected, fall through to the generic curl test in the next phase — the user can wire their tool later.

**PAUSE** — wait for the user to confirm they've set the env var (or that they're going to use the curl test instead).

---

## Phase 4.5: Wire MCP server

**EXPLAIN:** "The proxy also exposes an MCP server at \`http://localhost:${port}/api/mcp\`. Your AI agent can query logs, replay requests, and test providers through it — no need to leave the editor. We'll add an \`mcpServers\` entry so your agent picks it up automatically."

**DO:** Add (or merge) an \`mcpServers\` entry in the user's Claude Code config. The file is \`~/.claude.json\` on all platforms; the MCP spec entry uses HTTP Streamable transport:

\`\`\`json
// ~/.claude.json  (merge into existing mcpServers)
{
  "mcpServers": {
    "llm-inspector": {
      "type": "http",
      "url": "http://localhost:${port}/api/mcp"
    }
  }
}
\`\`\`

If \`mcpServers\` already exists, add \`llm-inspector\` as a new key — don't clobber existing entries.

PowerShell one-liner that creates the file if missing, or merges if present:

\`\`\`powershell
$cfg = Join-Path $env:USERPROFILE ".claude.json"
if (Test-Path $cfg) {
  $doc = Get-Content $cfg -Raw | ConvertFrom-Json
} else {
  $doc = [pscustomobject]@{ mcpServers = [pscustomobject]@{} }
}
if (-not ($doc.PSObject.Properties.Name -contains "mcpServers")) {
  $doc | Add-Member -NotePropertyName mcpServers -NotePropertyValue ([pscustomobject]@{})
}
$doc.mcpServers | Add-Member -NotePropertyName "llm-inspector" -NotePropertyValue ([pscustomobject]@{
  type = "http"
  url  = "http://localhost:${port}/api/mcp"
}) -Force
$doc | ConvertTo-Json -Depth 10 | Set-Content $cfg -Encoding UTF8
\`\`\`

**DO:** Verify the handshake. The MCP \`initialize\` request should return 200 with a \`serverInfo\` payload — that proves the server is mounted and reachable:

\`\`\`bash
curl -sS -X POST "http://localhost:${port}/api/mcp" \\
  -H "Content-Type: application/json" \\
  -H "Accept: application/json, text/event-stream" \\
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "initialize",
    "params": {
      "protocolVersion": "2025-03-26",
      "capabilities": {},
      "clientInfo": { "name": "onboard-check", "version": "0" }
    }
  }'
# expect: HTTP 200, body contains "result" with serverInfo.name = "llm-inspector"
\`\`\`

After the handshake, issue a \`tools/list\` to confirm the tool catalog is reachable:

\`\`\`bash
SESSION=<session-id-from-initialize-response>
curl -sS -X POST "http://localhost:${port}/api/mcp" \\
  -H "Content-Type: application/json" \\
  -H "Accept: application/json, text/event-stream" \\
  -H "mcp-session-id: $SESSION" \\
  -d '{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}'
# expect: a result.tools array with at least 1 entry
\`\`\`

**PAUSE** — if \`initialize\` returns non-200, show the user the proxy log and re-check the JSON syntax. If it returns 200 but \`tools/list\` fails, the server is up but the session wasn't carried over — re-use the \`mcp-session-id\` header from the first response.

---

## Phase 5: First capture

**EXPLAIN:** "Let's prove the proxy works end-to-end. We'll send one real request through it and confirm the log shows up in the API. A 401/403 from the upstream is fine — the point is that the *request* reaches the proxy."

**DO:** Fire a minimal Anthropic-format request through the proxy. This works regardless of which tool the user wired up:

\`\`\`bash
curl -sS -X POST "http://localhost:${port}/proxy/v1/messages" \\
  -H "Content-Type: application/json" \\
  -H "anthropic-version: 2023-06-01" \\
  -H "x-api-key: \${LLM_INSPECTOR_API_KEY:-sk-no-key-needed-for-routing}" \\
  -d '{"model":"claude-3-5-sonnet-20241022","max_tokens":1,"messages":[{"role":"user","content":"ping"}]}'
\`\`\`

**DO:** Poll the logs API for up to 5 seconds. A 200 with at least one entry means success:

\`\`\`bash
for i in $(seq 1 10); do
  resp=$(curl -sS "http://localhost:${port}/api/logs?limit=1")
  count=$(echo "$resp" | grep -o '"total":[0-9]*' | head -1 | grep -o '[0-9]*$')
  if [ "\${count:-0}" -ge 1 ]; then
    echo "captured"
    break
  fi
  sleep 0.5
done
\`\`\`

**PAUSE** — show the user the captured log entry (id, status, model, elapsed). If the count never reached 1, the proxy didn't see the request — re-check the env var and the proxy log.

---

## Phase 6: Tour & wrap

**EXPLAIN:** "Everything's working. Here's the cheat sheet for the Web UI and the supporting surfaces:"

- **Web UI**: \`http://localhost:${port}/\` — collapsible log rows, per-tab Copy/Expand in the log header, Diff with Raw (request body), Diff with Previous (compare adjacent requests), Replay (re-send a request), Export (JSON ZIP).
- **MCP server**: \`http://localhost:${port}/api/mcp\` — connect from your coding agent to query logs, replay, and test providers without leaving the editor. Look for the "MCP Ready" badge in the Web UI header.
- **REST API**: \`/api/logs\`, \`/api/sessions\`, \`/api/providers\` — for scripting and shell-based inspection.
- **Stop the proxy**:

  \`\`\`bash
  # Unix / macOS
  lsof -ti:${port} | xargs -r kill -9

  # Windows PowerShell
  Get-NetTCPConnection -LocalPort ${port} | ForEach-Object { Stop-Process -Id \\$_.OwningProcess -Force }
  \`\`\`

- **Re-run onboard**: \`llm-inspector onboard --force\` refreshes this skill.
- **Full docs**: see the project README (linked from the Web UI footer).

**PAUSE** — let the user know they can come back to this skill at any time via \`/llm-inspector:onboard\` if they want a refresher, and call out that \`/llm-inspector:onboard --skip-tool-wire\` is the way to re-run later phases without re-detecting the tool.

You're done. Happy inspecting.
`;
}
