# InsightReply API 接口文档

> **Base URL**：`https://<YOUR_SERVER>/api/v1`
> **认证方式**：Bearer Token (JWT)
> **内容类型**：`application/json`

---

## 通用响应格式

### 成功响应
```json
{
  "code": 200,
  "message": "success",
  "data": { ... }
}
```

### 错误响应
```json
{
  "code": 4001,
  "message": "具体的错误描述",
  "data": null
}
```

### HTTP Status Code 规范

| HTTP Status | 使用场景 |
|-------------|---------|
| `200 OK` | 正常响应 |
| `201 Created` | 资源创建成功 |
| `400 Bad Request` | 请求参数错误 (对应 code 4xxx) |
| `401 Unauthorized` | 未认证或 Token 过期 |
| `403 Forbidden` | 权限不足（如 Free 用户访问 Pro 功能） |
| `429 Too Many Requests` | 触发 Rate Limit |
| `500 Internal Server Error` | 服务端异常 (对应 code 5xxx) |
| `502 Bad Gateway` | 上游服务（如 LLM）不可用 |

### 业务错误码速查表

| Code | 含义 |
|------|------|
| `4001` | 请求体解析失败 / 参数缺失 |
| `4002` | 必填字段为空 |
| `4003` | 权限不足（Tier 限制） |
| `4004` | 资源不存在 |
| `4005` | Rate Limit 超限 |
| `4010` | 未认证 / Token 无效 |
| `4011` | Token 已过期 |
| `5001` | 数据库读写错误 |
| `5002` | LLM 调用失败 |
| `5003` | 外部服务超时 |

---

## 认证相关

### POST `/auth/register` — 用户注册

**请求体**：
```json
{
  "email": "user@example.com",
  "password": "securePassword123"
}
```

**成功响应**：
```json
{
  "code": 201,
  "message": "success",
  "data": {
    "user_id": "uuid-xxxx",
    "access_token": "eyJhbG...",
    "refresh_token": "eyJhbG..."
  }
}
```

---

### POST `/auth/login` — 用户登录

**请求体**：
```json
{
  "email": "user@example.com",
  "password": "securePassword123"
}
```

**成功响应**：
```json
{
  "code": 200,
  "message": "success",
  "data": {
    "access_token": "eyJhbG...",
    "refresh_token": "eyJhbG...",
    "user": {
      "id": "uuid-xxxx",
      "email": "user@example.com",
      "subscription_tier": "Free",
      "identity_label": "独立开发者"
    }
  }
}
```

---

### POST `/auth/refresh` — 刷新 Token

**请求体**：
```json
{
  "refresh_token": "eyJhbG..."
}
```

---

## AI 评论生成 (需认证)

### POST `/ai/generate` — 生成评论

**请求头**：
```
Authorization: Bearer <access_token>
```

**请求体**：
```json
{
  "tweet_content": "AI agents are going to replace 80% of SaaS tools in the next 2 years.",
  "strategy": "all",
  "identity": "AI 创始人",
  "language": "en",
  "max_length": 280
}
```

| 字段 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `tweet_content` | string | ✅ | 目标推文原文 |
| `strategy` | string | ❌ | `cognitive_upgrade` / `contrarian` / `data_supplement` / `empathy` / `founder_exp` / `all`（默认 `all`） |
| `identity` | string | ❌ | 用户身份标签，默认使用用户 Profile 中的设置 |
| `language` | string | ❌ | 输出语言，`en` / `zh` / `auto`（默认 `auto`，跟随原推文语言） |
| `max_length` | int | ❌ | 最大字符数，默认 280 |

**成功响应**：
```json
{
  "code": 200,
  "message": "success",
  "data": {
    "tweet_id": "optional-if-known",
    "replies": [
      {
        "strategy": "cognitive_upgrade",
        "label": "认知升级型",
        "candidates": [
          "Most people are thinking about this wrong. The real shift isn't agents replacing SaaS — it's agents making SaaS invisible. The UI layer vanishes, but the data layer matters more than ever.",
          "Hot take: agents won't replace SaaS. They'll rebuild it. Every workflow tool becomes an agent orchestrator. The winners know this already."
        ]
      },
      {
        "strategy": "contrarian",
        "label": "反向观点型",
        "candidates": ["..."]
      }
    ],
    "usage": {
      "prompt_tokens": 320,
      "completion_tokens": 580,
      "total_tokens": 900
    }
  }
}
```

---

## 用户配置 (需认证)

### GET `/users/me` — 获取当前用户信息

**成功响应**：
```json
{
  "code": 200,
  "message": "success",
  "data": {
    "id": "uuid-xxxx",
    "email": "user@example.com",
    "subscription_tier": "Pro",
    "identity_label": "AI 创始人",
    "daily_usage": { "generate": 5, "limit": -1 },
    "created_at": "2026-02-01T00:00:00Z"
  }
}
```

### PUT `/users/me/preferences` — 更新用户偏好

**请求体 (可增量更新)**：
```json
{
  "identity_label": "SaaS Builder",
  "language_preference": "zh"
}
```

---

## 监控配置 (需认证)

### POST `/monitors/keywords` — 添加关键词监控

**请求体**：
```json
{
  "keyword": "AI agent"
}
```

### GET `/monitors/keywords` — 获取关键词列表

### DELETE `/monitors/keywords/{id}` — 删除关键词

### POST `/monitors/accounts` — 添加账号监控

**请求体**：
```json
{
  "x_handle": "sama"
}
```

### GET `/monitors/accounts` — 获取监控账号列表

### DELETE `/monitors/accounts/{id}` — 删除监控账号

---

## 用户可配置系统 API (需认证)

### GET `/users/me/product_profiles` — 获取用户产品档案

**成功响应**：
```json
{
  "code": 200,
  "message": "success",
  "data": {
    "product_name": "InsightReply",
    "tagline": "AI-powered audience engagement",
    "domain": "SaaS",
    "key_features": "[\"Multi-LLM\", \"Custom Strategies\"]",
    "target_users": "Founders, Indie Hackers",
    "product_url": "https://insightreply.example.com",
    "competitors": "[\"ReplyGuy\", \"TweetHunter\"]",
    "relevance_keywords": "[\"marketing\", \"twitter growth\"]",
    "custom_context": "We focus on high-quality, non-spammy replies",
    "default_llm_provider": "anthropic",
    "default_llm_model": "claude-3-5-haiku-latest"
  }
}
```

### PUT `/users/me/product_profiles` — 更新用户产品档案

**请求体**：
接受与 GET 响应相同的 JSON 字段结构。

---

### GET `/users/me/strategies` — 获取自定义策略列表

**成功响应**：
```json
{
  "code": 200,
  "message": "success",
  "data": [
    {
      "id": "uuid-xxx",
      "strategy_key": "funny",
      "label": "幽默调侃型",
      "icon": "🤣",
      "description": "Make the reader laugh.",
      "prompt_template": "Reply to this with a witty joke: {tweet_content}",
      "few_shot_examples": "[]",
      "sort_order": 1
    }
  ]
}
```

### POST `/users/me/strategies` — 创建自定义策略
**请求体** 接受与 GET 列表中单项内容相同的结构（无需提供 id）。

### DELETE `/users/me/strategies/{id}` — 删除自定义策略

---

### GET `/monitors/competitors` — 获取竞品监控列表

**成功响应**：
```json
{
  "code": 200,
  "message": "success",
  "data": [
    {
      "id": "uuid-xxx",
      "brand_name": "CompetitorA",
      "x_handle": "@compa"
    }
  ]
}
```

### POST `/monitors/competitors` — 添加竞品监控
**请求体**：
```json
{
  "brand_name": "CompetitorA",
  "x_handle": "@compa"
}
```

### DELETE `/monitors/competitors/{id}` — 删除竞品监控

> 用户可定义自己正在推广的产品信息，系统会将其注入 Prompt，生成与产品领域高度关联的评论。

### GET `/users/me/product` — 获取产品档案

**成功响应**：
```json
{
  "code": 200,
  "message": "success",
  "data": {
    "product_name": "SwiftBiu",
    "tagline": "AI-powered short video creation tool",
    "domain": "AI Video Creation",
    "key_features": ["视频生成", "多语言配音", "AI 脚本"],
    "target_users": "内容创作者, 独立开发者, 出海团队",
    "product_url": "https://apps.apple.com/app/swiftbiu",
    "competitors": ["CapCut", "Descript", "Opus Clip"],
    "relevance_keywords": ["short video", "content creation", "AI dubbing", "video editing"],
    "custom_context": "We focus on multi-language video creation for global creators.",
    "default_llm_provider": "anthropic",
    "default_llm_model": "claude-3-5-haiku-latest"
  }
}
```

### PUT `/users/me/product` — 更新产品档案

**请求体**：（所有字段可选，只传需要更新的字段）
```json
{
  "product_name": "SwiftBiu",
  "tagline": "AI-powered short video creation tool",
  "domain": "AI Video Creation",
  "key_features": ["视频生成", "多语言配音", "AI 脚本"],
  "competitors": ["CapCut", "Descript"],
  "relevance_keywords": ["short video", "content creation"],
  "custom_context": "任意自定义的上下文信息，会被注入到生成 Prompt 中",
  "default_llm_provider": "anthropic",
  "default_llm_model": "claude-3-5-haiku-latest" // 支持前端列表选择，或用户手动输入自定义模型（如接入代理时的自有模型）
}
```

---

## 自定义策略 (需认证)

> 除系统内置的 5 种策略外，用户可创建自己的评论策略模板。

### GET `/users/me/strategies` — 获取策略列表（含系统内置 + 用户自定义）

**成功响应**：
```json
{
  "code": 200,
  "message": "success",
  "data": {
    "builtin": [
      { "strategy_key": "cognitive_upgrade", "label": "认知升级型", "icon": "🧠" },
      { "strategy_key": "contrarian", "label": "反向观点型", "icon": "🔥" }
    ],
    "custom": [
      {
        "id": "uuid-xxx",
        "strategy_key": "builder_story",
        "label": "创始人实战型",
        "icon": "🚀",
        "description": "以自身产品经验为论据，自然关联到我的产品",
        "prompt_template": "用 {identity} 的身份，基于 {product_name} 的开发经验，对这条推文写一条有洞察力的评论...",
        "few_shot_examples": ["We faced this exact problem building SwiftBiu..."]
      }
    ]
  }
}
```

### POST `/users/me/strategies` — 创建自定义策略

**请求体**：
```json
{
  "strategy_key": "builder_story",
  "label": "创始人实战型",
  "icon": "🚀",
  "description": "以自身产品经验为论据，自然关联到产品",
  "prompt_template": "用 {identity} 的身份，基于 {product_name} 的开发经验...",
  "few_shot_examples": [
    "We faced this exact problem building SwiftBiu. What worked for us was..."
  ]
}
```

### PUT `/users/me/strategies/{id}` — 更新自定义策略

### DELETE `/users/me/strategies/{id}` — 删除自定义策略

---

## 竞品监控 (需认证)

### POST `/monitors/competitors` — 添加竞品监控

**请求体**：
```json
{
  "brand_name": "CapCut",
  "x_handle": "CapCut"
}
```

### GET `/monitors/competitors` — 获取竞品监控列表

### DELETE `/monitors/competitors/{id}` — 删除竞品监控

---

## 系统 (无需认证)

### GET `/sys/config/llms` — 获取支持的 LLM 模型列表

> 用于前端渲染「重写 AI 引擎」的下拉菜单，由后端统一从环境变量 (`OPENAI_AVAILABLE_MODELS` 等) 下发。

**成功响应**：
```json
{
  "code": 200,
  "message": "success",
  "data": {
    "providers": [
      {
        "id": "openai",
        "name": "OpenAI (或兼容接口)",
        "models": ["gpt-4o", "gpt-4o-mini", "o1-mini"]
      },
      {
        "id": "anthropic",
        "name": "Anthropic Claude",
        "models": ["claude-3-5-sonnet-latest", "claude-3-5-haiku-latest"]
      },
      {
        "id": "deepseek",
        "name": "DeepSeek",
        "models": ["deepseek-chat", "deepseek-reasoner"]
      },
      {
        "id": "gemini",
        "name": "Google Gemini",
        "models": ["gemini-2.5-flash", "gemini-2.5-pro"]
      }
    ]
  }
}
```

### GET `/health` — 健康检查

**成功响应**：
```json
{
  "code": 200,
  "message": "ok",
  "data": {
    "status": "healthy",
    "db": "connected",
    "version": "1.0.0",
    "uptime": "2h30m"
  }
}
```
