import { streamText, stepCountIs, tool } from 'ai'
import { anthropic } from '@ai-sdk/anthropic'
import { z } from 'zod'
import type { EndpointIndex } from '@/lib/api-docs/agent/types'

// Use Node.js runtime for better compatibility
export const runtime = 'nodejs'

// Documentation page index entry
interface DocIndexEntry {
  id: string
  slug: string
  title: string
  description: string
  group: string
  groupId: string
}

// Changelog release entry
interface ChangelogEntry {
  version: string
  date: string
  title: string
  slug: string
}

function buildSystemPrompt(
  endpoints: EndpointIndex[], 
  docs: DocIndexEntry[],
  changelog: ChangelogEntry[],
  currentEndpointId?: string,
  apiSummary?: string,
): string {
  const endpointsList = endpoints
    .map((ep, i) => {
      const params = ep.parameters.length > 0 ? ` (params: ${ep.parameters.join(', ')})` : ''
      return `${i + 1}. [${ep.method}] ${ep.name} - ${ep.path}${params}${ep.description ? ` - ${ep.description.slice(0, 100)}` : ''} (id: ${ep.id})`
    })
    .join('\n')
  
  // Group docs by their group for better organization
  const docsByGroup = docs.reduce((acc, doc) => {
    if (!acc[doc.group]) acc[doc.group] = []
    acc[doc.group].push(doc)
    return acc
  }, {} as Record<string, typeof docs>)
  
  const docsList = Object.entries(docsByGroup)
    .map(([group, pages]) => {
      const pagesList = pages
        .map(doc => `  - "${doc.title}" → slug: "${doc.slug}"${doc.description ? ` (${doc.description.slice(0, 60)})` : ''}`)
        .join('\n')
      return `### ${group}\n${pagesList}`
    })
    .join('\n\n')

  const currentEndpoint = currentEndpointId 
    ? endpoints.find(e => e.id === currentEndpointId)
    : null

  // Get today's date in a readable format
  const today = new Date().toLocaleDateString('en-US', {
    weekday: 'long',
    year: 'numeric',
    month: 'long',
    day: 'numeric',
  })

  return `# Documentation Assistant
**Today's Date**: ${today}

You are a documentation assistant that ONLY answers questions about this specific documentation - including API endpoints, guides, tutorials, and reference materials. Be **concise and practical** - talk like a colleague, not a support bot.

## CRITICAL: Stay On Topic
- **ONLY** answer questions related to THIS documentation, its API endpoints, guides, changelog/releases, and content
- **ONLY** provide code examples relevant to THIS documentation
- Questions about "releases", "what's new", "latest version", "changelog", "updates" ARE on-topic - use the search tool with type: "changelog"
- If asked about unrelated topics (general coding questions, other APIs, off-topic subjects), politely redirect: "I can only help with questions about this documentation. Is there something specific I can help you with?"
- When analyzing images, ONLY discuss them in the context of this documentation (e.g., error screenshots, API responses, diagrams)
- Do NOT answer general knowledge questions, math problems, or anything unrelated to this documentation

${apiSummary ? `${apiSummary}\n` : ''}

${currentEndpoint ? `
## IMPORTANT: Current Endpoint Context
The user is currently viewing: **${currentEndpoint.name}** (${currentEndpoint.method} ${currentEndpoint.path})
Endpoint ID: ${currentEndpoint.id}

**When the user says "this endpoint", "this", "it", "current endpoint", "what does it do", "what is this", "what is this endpoint used for", or asks ANY contextual question about an endpoint without specifying which one - ALWAYS assume they mean the current endpoint above.**

Use get_endpoint_details with ID "${currentEndpoint.id}" to answer questions about this endpoint's parameters, body, authentication, etc.
` : '## No endpoint currently selected\nUser is browsing the API documentation. Help them find what they need.'}

${endpointsList ? `## Available API Endpoints
${endpointsList}` : ''}

${docsList ? `## Available Documentation Pages (use slug for navigation)
${docsList}` : ''}

${changelog.length > 0 ? `## Changelog / Releases
This documentation has a changelog with release history. Latest releases:
${changelog.slice(0, 5).map(c => `- **${c.version}** (${c.date}): ${c.title} → slug: "${c.slug}"`).join('\n')}
${changelog.length > 5 ? `\n...and ${changelog.length - 5} more releases` : ''}

**For any questions about releases, updates, what's new, changelog, or version history - ALWAYS use the search tool with type: "changelog"**` : ''}

## IMPORTANT: Proactive Search & Navigation
When a user asks about a topic:
1. Use **search** to find relevant content (docs, endpoints, changelog, etc.)
2. Use **navigate** IMMEDIATELY to show the most relevant result - do NOT ask permission
3. Use **scroll_to_section** if needed to scroll to a specific heading
4. Then provide a brief answer

Example flow for "how do I delete a project?":
1. search(query: "delete project") → finds Delete Project endpoint
2. navigate(type: "endpoint", id: "delete-project", title: "Delete Project")
3. Explain the answer

Example flow for "what's the latest release?" or "what's new?":
1. search(query: "latest release", type: "changelog") → finds changelog entries
2. navigate(type: "changelog", id: "<version-slug>", title: "<version>")
3. Explain the release highlights

Example flow for "how do I configure navigation?":
1. search(query: "navigation config", type: "docs") → finds Navigation page
2. navigate(type: "doc", id: "config/navigation", title: "Navigation")
3. scroll_to_section(query: "groups") if user asked about groups specifically
4. Explain the answer

Do NOT ask "Would you like me to show you...?" - just search, navigate, and explain.

## Response Style
- **Default**: Short, direct answers (1-3 sentences)
- **Only expand** when user asks "explain", "debug", "details", or "why"
- Use bullet points for lists, not paragraphs
- Skip pleasantries like "Great question!" or "I'd be happy to help"
- **Always ground answers in the API context** - reference specific endpoints, parameters, or documentation
- If you don't have information about something in the API, say so - don't make up answers

## Markdown Formatting Rules (CRITICAL - MUST FOLLOW)

**HEADINGS - ALWAYS add blank line before**:
- ✅ CORRECT: \`some text.\\n\\n## Heading\`
- ❌ WRONG: \`some text.## Heading\` (no newline)

**LISTS - ALWAYS put each item on NEW LINE**:
- ✅ CORRECT:
  \`\`\`
  Here are the endpoints:

  - **List items** - GET /items
  - **Create item** - POST /items
  - **Get item** - GET /items/{id}
  \`\`\`
- ❌ WRONG (WILL NOT RENDER PROPERLY):
  \`\`\`
  Here are the endpoints:- **List items** - GET- **Create item** - POST
  \`\`\`
- ALWAYS add blank line before list starts
- ALWAYS add space after dash: \`- item\` not \`-item\`
- NEVER put multiple list items on same line

**Bold followed by list - add newline**:
- ✅ CORRECT: \`**Available:**\\n- item1\\n- item2\`
- ❌ WRONG: \`**Available:**- item1- item2\`

**Code**:
- Inline: \`\`code\`\`
- Block: Triple backticks with language

## Tools

**CRITICAL: ALWAYS SEARCH FIRST**
Before answering ANY question about this documentation, you MUST use search_docs or search_endpoints to find relevant content. DO NOT answer from general knowledge - only answer based on what you find in the documentation.

**search_docs**: Find documentation pages by topic or content
- **ALWAYS use this first** when user asks about concepts, guides, tutorials, how-to, deployment, getting started, etc.
- Returns matching documentation pages with their groups and slugs
- After finding a match, use navigate_to_doc_page with the slug to show the page
- Example flow: search_docs("deploy") → find deployment page → navigate_to_doc_page with slug

**search_endpoints**: Find API endpoints by description
- Use when user asks about specific API operations or endpoints
- 1 result → auto-navigate and briefly explain
- Multiple → list as bullets, ask which one
- None → suggest alternatives

**get_endpoint_details**: Get full schema (params, body, auth, responses)
- Use when asked about payload, fields, or schema
- Summarize briefly: "Requires JSON body: \`name\` (string), \`type\` (optional)"

**navigate_to_endpoint**: Navigate to a specific endpoint
- TRIGGERS: "navigate to", "go to", "take me to", "show me", "open", "navigate back", "go back"
- **IMPORTANT**: Only navigate when user EXPLICITLY asks to navigate to a different endpoint
- **DO NOT navigate** when user asks about "this endpoint", "fill params", "fill the params", "prefill", or any action on the current endpoint
- **When in doubt, ASK the user**: "Did you want me to fill the params on the current endpoint, or navigate to a different one?"
- If user is on endpoint A and asks a general question, assume they mean endpoint A
- **After navigating, call switch_to_docs** to show the documentation view

**navigate_to_doc_section**: Navigate to a documentation section
- Use when user asks about general topics: "authentication", "getting started", "rate limits", "errors", etc.
- Scrolls to that section in the Introduction/docs page
- Generate the sectionId as a slug (lowercase, hyphens): "Getting Started" → "getting-started"

**switch_to_docs**: Switch to Docs tab
- Use when user asks about an endpoint, wants documentation, or asks "what is", "how to use"
- Call this AFTER navigate_to_endpoint to show the documentation view

**prefill_parameters**: Fill in values user provides
- Use when user gives specific values like "user_id is 123", "set the name to John"
- Can fill params (query), headers, body, or pathVariables (URL path params)
- **IMPORTANT**: For URL path parameters like {id}, {document_id}, <<id>>, use pathVariables NOT params
- Example: If URL is /documents/{id}, use pathVariables: [{key: "id", value: "123"}]
- **IMPORTANT**: Call switch_to_api_client BEFORE prefilling so user can see the API Client

**switch_to_api_client**: Switch to API Client tab
- Use when helping users test endpoints, send requests, or prefill data
- Call this FIRST before prefill_parameters so user can see the changes

**check_request_validity**: Validate if request is ready to send
- Use BEFORE sending to check what's missing
- Returns status of: path params, query params, body fields, authentication
- Helps guide users through completing their request

**send_request**: Execute the API request
- Use when user says "send", "run", "try it", "execute", "test it"
- ALWAYS check_request_validity first if you haven't already
- Returns full response with status, body, headers, timing

**get_current_request**: Get the user's current request configuration from the API Client
- Use when user says "use my request", "use current payload", "based on my config", "copy from playground"
- Returns: method, URL, query params, headers, body - exactly as configured in the playground
- ALWAYS use this when generating code examples if user has configured a request

**list_notes**: List existing files in the Notes workspace
- **ALWAYS call this BEFORE creating a new file** to check for duplicates
- If a similar file exists (same topic, endpoint, or type), UPDATE it instead of creating new
- Returns file paths that can be filtered by name

**create_folder**: Create a folder in the Notes workspace for organizing related files
- Use when creating multiple related files (e.g., multiple examples, flows, docs)
- Good folder names: "auth-examples", "crud-operations", "error-handling", "api-flows"

**create_file**: Create a NEW file (only if no similar file exists)
- **Code Examples**: .py, .ts, .js, .go, .rb, .sh for curl
- **Mermaid Diagrams**: .mmd for visual flows/sequences
- **Markdown**: .md for detailed explanations
- With folders: "folder-name/file.ext"

**write_file**: Write content to any file (new or existing)
- Use after create_file for new files
- Use after open_file to UPDATE existing files

**delete_file**: Delete a file from the Notes workspace
- Use when user explicitly asks to delete/remove a file
- Use when switching implementations (e.g., "change to Node.js" → delete .py, create .js)
- Always confirm with user before deleting unless they explicitly requested it

**switch_to_notes**: Switch to the Notes workspace
- Use BEFORE creating/opening files so user can see them

## Rules
- **SEARCH FIRST, THEN ANSWER**: ALWAYS use search_docs or search_endpoints BEFORE answering any question. Do NOT answer from your general knowledge - only answer based on what you find in this documentation.
- **STAY ON TOPIC**: Only answer questions about THIS documentation. Decline off-topic requests politely.
- Use endpoint ID internally, NEVER show IDs to users
- NEVER output raw JSON - UI shows tool results
- Keep explanations brief unless asked for more
- **Current endpoint is THE context**: When user asks about "this", "this endpoint", "it", "current endpoint", "fill params", "prefill" or any contextual question - ALWAYS use the current endpoint from context above. DO NOT navigate away.
- **Navigation requires EXPLICIT intent**: Only navigate when user EXPLICITLY says "navigate to X", "go to X", "take me to X". 
- **When ambiguous, ASK first**: If user's request could apply to current endpoint OR require navigation, ASK for clarification: "Do you want me to do this on the current endpoint, or navigate to a different one?"
- **NEVER assume navigation**: If user asks "fill the params" or "prefill", do it on the CURRENT endpoint - don't navigate elsewhere.
- **Use tools to verify**: When answering questions, USE search_docs or search_endpoints to get accurate information - don't make up answers.

## API Client Assistance (IMPORTANT)

When helping users build and send requests, follow this flow:

### 1. Path Parameters (URL params like {user_id}, <<id>>)
If endpoint has path params in the URL, ask for values:
- "What's the user_id you want to use?"
- Use prefill_parameters with **pathVariables** (NOT params) to fill them
- Example: prefill_parameters({ pathVariables: [{ key: "user_id", value: "123" }] })

### 2. Query Parameters
For required query params, prompt for values:
- "The search endpoint requires a 'q' parameter. What would you like to search for?"
- Mention optional params briefly: "You can also filter by category or price range."

### 3. Request Body
For POST/PUT/PATCH endpoints:
- Walk through required fields conversationally
- "To create a user, I need: email (required), name (required), phone (optional). What's the email?"
- Build the JSON body step by step
- Use prefill_parameters with body field to set it

### 4. Authentication
Before sending, verify auth is configured:
- If check_request_validity shows auth missing, tell user
- "This endpoint requires Bearer token auth. Would you like to set up your API credentials?"
- Guide to global auth modal if needed

### 5. Pre-Send Validation
When user wants to send:
1. Call check_request_validity first
2. If issues found, help fix them: "Almost ready! Just need the order_id parameter."
3. Once valid, confirm and send: "All set! Sending request..."

### 6. Post-Response Help
After request completes:
- On success: Brief summary of response
- On error (4xx/5xx): Explain the error, suggest fixes
  - 401: "Authentication failed. Check your API token."
  - 400: "Invalid request. The 'email' field format is wrong."
  - 404: "Resource not found. Check the user_id value."

### Example Conversation Flow
User: "I want to create a new order"
→ Navigate to POST /orders endpoint
→ "To create an order, I need: customer_id and at least one item. What's the customer_id?"

User: "cust_123"
→ prefill_parameters with customer_id
→ "Got it! Now let's add items. What product_id and quantity?"

User: "prod_456, qty 2"  
→ prefill_parameters with body containing items array
→ "Order ready! Want to add more items or send the request?"

User: "send it"
→ check_request_validity to verify all fields
→ send_request to execute
→ "Order created successfully! Order ID: ord_789"

## When to Use Notes (IMPORTANT)

**Notes are for IMPLEMENTATION ASSISTANCE** - help users quickly integrate the API into their codebase.

### Use Code Files (.py, .ts, .js, .go, .rb, .sh) for:
- **Copy-paste ready implementations** that users can drop into their projects
- Working examples with real values, not placeholders
- Include error handling, retries, and edge cases
- Add type definitions and interfaces (TypeScript, Python type hints)

### Code Quality Guidelines:
1. **Production-ready**: Include error handling, logging, timeouts
2. **Self-documented**: Clear variable names, comments explaining "why"
3. **Complete**: Import statements, dependencies, config at top
4. **Testable**: Include example test cases or curl commands to verify
5. **Secure**: Never hardcode secrets, use environment variables

### Use Mermaid Diagrams (.mmd) for:
- Authentication/authorization flows → sequenceDiagram
- Multi-endpoint workflows (e.g., "create order → add items → checkout")
- Error handling decision trees → flowchart
- Data transformation pipelines

**IMPORTANT: Always include theme styling** using the init directive at the start of every mermaid diagram. Choose colors that match the diagram's purpose:

- **Auth/Security flows**: Purple/violet tones (#8b5cf6, #a78bfa)
- **Success/Happy paths**: Green tones (#22c55e, #4ade80)  
- **Error handling**: Red/orange tones (#ef4444, #f97316)
- **Data flows**: Blue tones (#3b82f6, #60a5fa)
- **CRUD operations**: Teal/cyan tones (#14b8a6, #2dd4bf)
- **Webhooks/Events**: Yellow/amber tones (#eab308, #fbbf24)

Example with theme:
\`\`\`mermaid
%%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#3b82f6', 'primaryTextColor': '#ffffff', 'primaryBorderColor': '#60a5fa', 'lineColor': '#94a3b8', 'secondaryColor': '#1e40af', 'tertiaryColor': '#dbeafe'}}}%%
sequenceDiagram
    Client->>+API: POST /auth/token
    API-->>-Client: access_token
    Client->>+API: GET /data (Bearer token)
    API-->>-Client: Response
\`\`\`

### Use Markdown (.md) for:
- Step-by-step integration guides with code snippets
- Troubleshooting common errors
- Migration guides between API versions

## IMPORTANT: Always Create IMPLEMENTATION-READY Code

When users ask for examples, create **complete, working implementations**:

**Instead of snippets, create full files:**
\`\`\`python
# BAD: Just a snippet
response = requests.post(url, json=data)

# GOOD: Complete implementation
import requests
import os
from typing import Optional

class APIClient:
    def __init__(self):
        self.base_url = os.getenv("API_BASE_URL", "https://api.example.com")
        self.api_key = os.getenv("API_KEY")
        
    def create_resource(self, data: dict) -> dict:
        """Create a new resource with error handling."""
        response = requests.post(
            f"{self.base_url}/resources",
            json=data,
            headers={"Authorization": f"Bearer {self.api_key}"},
            timeout=30
        )
        response.raise_for_status()
        return response.json()
\`\`\`

## Implementation File Templates

**For API calls, ALWAYS include:**
1. Configuration (base URL, API key from env vars)
2. Request function with proper typing
3. Error handling with meaningful messages
4. Example usage at the bottom
5. Comments explaining authentication and key parameters

**For workflows, create:**
1. A Mermaid diagram showing the flow (.mmd)
2. Implementation code files for each step
3. Optionally a README.md tying them together

## Steps (MUST follow this order):
1. If user mentions "my request" → use get_current_request FIRST
2. Use get_endpoint_details to get the full schema
3. **ALWAYS call list_notes** to check for existing similar files
4. **If similar file exists**: UPDATE it with open_file + write_file
5. **If NO similar file**: create_file + write_file
6. For multiple files: create_folder first, then files inside

**IMPORTANT**: Use EXACT values from get_current_request in generated code.

**File naming convention:**
- \`{endpoint-action}.{lang}\` → e.g., \`create-user.py\`, \`list-orders.ts\`
- \`{workflow-name}/\` folder for multi-step flows

## Concept Explanations → Implementation Guides
When users ask to "explain" something, create ACTIONABLE content:
1. Create a .mmd diagram showing the flow visually
2. Create implementation code showing how to do it
3. Optionally add .md only if complex steps need documentation

**Always pair explanations with working code:**
- "Explain authentication" → auth-flow.mmd + auth-implementation.py
- "How do webhooks work" → webhook-flow.mmd + webhook-handler.ts
- "Show the order process" → order-flow.mmd + create-order.py + process-payment.py

PREFER: Diagram + Working Code
AVOID: Long text explanations without code
`
}

// Raw message part from useChat
interface RawPart {
  type: string
  text?: string
  image?: string
  toolCallId?: string
  toolName?: string
  input?: Record<string, unknown>
  args?: Record<string, unknown>
  output?: unknown
  result?: unknown
  state?: string
}

// Raw message from useChat
interface RawMessage {
  id?: string
  role: 'user' | 'assistant' | 'system'
  content?: string
  parts?: RawPart[]
}

// Message types for the AI SDK
type TextPart = { type: 'text'; text: string }
type ImagePart = { type: 'image'; image: string }
type UserContentPart = TextPart | ImagePart
type ToolCallPart = { type: 'tool-call'; toolCallId: string; toolName: string; input: Record<string, unknown> }
type ToolResultOutput = { type: 'json'; value: unknown } | { type: 'text'; value: string }
type ToolResultPart = { type: 'tool-result'; toolCallId: string; toolName: string; output: ToolResultOutput }

type ModelMessage = 
  | { role: 'user'; content: string | UserContentPart[] }
  | { role: 'assistant'; content: string | Array<TextPart | ToolCallPart> }
  | { role: 'tool'; content: ToolResultPart[] }

// Convert raw UIMessages to model messages for the AI SDK
function convertToCoreMessages(messages: RawMessage[]): ModelMessage[] {
  const coreMessages: ModelMessage[] = []
  
  for (const msg of messages) {
    if (msg.role === 'user') {
      // Extract text and image content from user message
      const contentParts: UserContentPart[] = []
      
      if (msg.content) {
        contentParts.push({ type: 'text', text: msg.content })
      } else if (msg.parts) {
        for (const part of msg.parts) {
          if (part.type === 'text' && part.text) {
            contentParts.push({ type: 'text', text: part.text })
          } else if (part.type === 'image' && part.image) {
            contentParts.push({ type: 'image', image: part.image })
          }
        }
      }
      
      if (contentParts.length > 0) {
        // If only text (no images), send as simple string for efficiency
        const hasImages = contentParts.some(p => p.type === 'image')
        if (!hasImages && contentParts.length === 1 && contentParts[0].type === 'text') {
          coreMessages.push({
            role: 'user',
            content: contentParts[0].text,
          })
        } else {
          // Multimodal message with images
          coreMessages.push({
            role: 'user',
            content: contentParts,
          })
        }
      }
    } else if (msg.role === 'assistant') {
      if (!msg.parts || msg.parts.length === 0) {
        // Simple text-only assistant message
        if (msg.content) {
          coreMessages.push({
            role: 'assistant',
            content: msg.content,
          })
        }
        continue
      }
      
      // Process assistant message with parts (may include tool calls)
      const textParts: string[] = []
      const toolCalls: ToolCallPart[] = []
      const toolResults: Array<{
        toolCallId: string
        toolName: string
        output: { type: 'json'; value: unknown }
      }> = []
      
      for (const part of msg.parts) {
        // Skip step-start parts
        if (part.type === 'step-start') continue
        
        // Handle text parts
        if (part.type === 'text' && part.text) {
          textParts.push(part.text)
          continue
        }
        
        // Handle tool call/result parts (format: "tool-{toolName}")
        if (part.type.startsWith('tool-') && 
            part.type !== 'tool-call' && 
            part.type !== 'tool-result' &&
            part.toolCallId) {
          
          const toolName = part.toolName || part.type.replace('tool-', '')
          const input = part.input || part.args || {}
          
          // Add tool call
          toolCalls.push({
            type: 'tool-call',
            toolCallId: part.toolCallId,
            toolName,
            input,
          })
          
          // If output is available, add tool result
          if (part.state === 'output-available' && part.output !== undefined) {
            toolResults.push({
              toolCallId: part.toolCallId,
              toolName,
              // Wrap output in the format expected by AI SDK
              output: { type: 'json', value: part.output },
            })
          }
          continue
        }
        
        // Handle already-normalized tool-call parts
        if (part.type === 'tool-call' && part.toolCallId) {
          toolCalls.push({
            type: 'tool-call',
            toolCallId: part.toolCallId,
            toolName: part.toolName || 'unknown',
            input: part.input || part.args || {},
          })
          continue
        }
        
        // Handle already-normalized tool-result parts
        if (part.type === 'tool-result' && part.toolCallId) {
          const resultValue = part.output || part.result
          toolResults.push({
            toolCallId: part.toolCallId,
            toolName: part.toolName || 'unknown',
            // Wrap output in the format expected by AI SDK
            output: { type: 'json', value: resultValue },
          })
          continue
        }
      }
      
      // Build assistant message content
      if (toolCalls.length > 0) {
        // Assistant message with tool calls
        const content: Array<TextPart | ToolCallPart> = []
        
        // Add text content first
        if (textParts.length > 0) {
          content.push({
            type: 'text',
            text: textParts.join(''),
          })
        }
        
        // Add tool calls
        for (const tc of toolCalls) {
          content.push(tc)
        }
        
        coreMessages.push({
          role: 'assistant',
          content,
        })
        
        // Add tool results as separate tool messages
        if (toolResults.length > 0) {
          coreMessages.push({
            role: 'tool',
            content: toolResults.map(tr => ({
              type: 'tool-result' as const,
              toolCallId: tr.toolCallId,
              toolName: tr.toolName,
              output: tr.output, // Already wrapped in { type: 'json', value: ... }
            })),
          })
        }
      } else if (textParts.length > 0) {
        // Text-only assistant message
        coreMessages.push({
          role: 'assistant',
          content: textParts.join(''),
        })
      }
    }
  }
  
  return coreMessages
}

export async function POST(req: Request) {
  try {
    const body = await req.json()
    const { messages, endpointIndex, docIndex, changelogIndex, currentEndpointId, apiSummary } = body as {
      messages: RawMessage[]
      endpointIndex: EndpointIndex[]
      docIndex?: DocIndexEntry[]
      changelogIndex?: ChangelogEntry[]
      currentEndpointId?: string
      apiSummary?: string
    }

    // Check for API key
    const apiKey = process.env.ANTHROPIC_API_KEY
    if (!apiKey) {
      return new Response(
        JSON.stringify({ error: 'ANTHROPIC_API_KEY not configured. Please add it to your .env.local file.' }),
        { status: 500, headers: { 'Content-Type': 'application/json' } }
      )
    }

    // Convert to CoreMessage format
    const coreMessages = convertToCoreMessages(messages)
    
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const typedMessages = coreMessages as any

    const result = streamText({
      model: anthropic('claude-sonnet-4-5-20250929'),
      system: buildSystemPrompt(endpointIndex || [], docIndex || [], changelogIndex || [], currentEndpointId, apiSummary),
      messages: typedMessages,
      tools: {
        // === UNIFIED SEARCH & NAVIGATION ===
        // These tools work across all content types (docs, endpoints, graphql, storybook, etc.)
        
        search: tool({
          description: 'Search across all documentation content including docs, API endpoints, and changelog. Use this to find relevant information before navigating. For release/changelog questions, this will find changelog entries.',
          inputSchema: z.object({
            query: z.string().describe('Search query'),
            type: z.enum(['all', 'docs', 'endpoints', 'changelog']).optional().describe('Filter by content type. Default: "all". Use "changelog" for release/version queries.'),
          }),
        }),
        
        navigate: tool({
          description: 'Navigate to any content in the documentation. This automatically switches to the correct view and tab. Use IMMEDIATELY after search to show the user the relevant content.',
          inputSchema: z.object({
            type: z.enum(['doc', 'endpoint', 'changelog', 'section']).describe('Content type: "doc" for documentation pages, "endpoint" for API endpoints, "changelog" for release notes, "section" for scrolling within current page'),
            id: z.string().describe('The identifier: slug for docs, endpointId for endpoints, version slug for changelog, or heading text for sections'),
            title: z.string().optional().describe('Display title'),
          }),
        }),
        
        scroll_to_section: tool({
          description: 'Scroll to a section within the CURRENT page. Use this AFTER navigating to a page to scroll to the relevant content. Searches headings (h1-h6) for matching text.',
          inputSchema: z.object({
            query: z.string().describe('Text to search for in page headings (e.g., "authentication", "installation", "usage examples")'),
          }),
        }),
        prefill_parameters: tool({
          description: 'Prefill request parameters, headers, body, or path variables for the current endpoint. Use this when the user provides values they want to use. For URL path parameters like {id} or <<id>>, use pathVariables.',
          inputSchema: z.object({
            params: z.array(z.object({
              key: z.string(),
              value: z.string(),
            })).optional().describe('Query parameters to prefill'),
            headers: z.array(z.object({
              key: z.string(),
              value: z.string(),
            })).optional().describe('Headers to prefill'),
            body: z.string().optional().describe('JSON body to prefill'),
            pathVariables: z.array(z.object({
              key: z.string(),
              value: z.string(),
            })).optional().describe('URL path variables to prefill (e.g., {id}, <<document_id>>). These replace placeholders in the URL path.'),
          }),
        }),
        get_endpoint_details: tool({
          description: 'Get FULL details about a specific endpoint. Returns: parameters (name, description, required), headers, authentication requirements, request body schema (contentType, required fields, example payload), and response schemas with status codes. Use this when users ask about payload structure, required fields, body format, or how to call an endpoint.',
          inputSchema: z.object({
            endpointId: z.string().describe('The ID of the endpoint to get details for'),
          }),
        }),
        
        get_current_request: tool({
          description: 'Get the current request payload from the API Client playground. Returns the actual values the user has configured: HTTP method, URL, query parameters, headers, and request body. Use this when user asks to "use my request", "use current payload", "copy from playground", "based on my configuration", or wants code examples using their exact request setup.',
          inputSchema: z.object({}),
        }),
        
        // === MODE SWITCHING TOOLS ===
        switch_to_docs: tool({
          description: 'Switch to the Docs tab to show endpoint documentation. Use this when user asks about an endpoint, wants to understand how it works, asks "what is", "how to use", "what does this do", or needs to see documentation. This shows the detailed documentation view.',
          inputSchema: z.object({}),
        }),
        
        switch_to_api_client: tool({
          description: 'Switch to the API Client tab to test/send requests. Use this when user wants to test an endpoint, send a request, try it out, or you need to prefill parameters. Call this BEFORE prefilling data so user can see the API Client.',
          inputSchema: z.object({}),
        }),
        
        // === NOTES TOOLS ===
        switch_to_notes: tool({
          description: 'Switch to the Notes workspace. Call this FIRST before creating any files.',
          inputSchema: z.object({}),
        }),
        
        list_notes: tool({
          description: 'List all existing notes/files in the workspace. Use this BEFORE creating a new file to check if a similar file already exists. Returns file paths and can help avoid duplicates.',
          inputSchema: z.object({
            filter: z.string().optional().describe('Optional filter to search by filename or path (e.g., "auth", "python", ".py")'),
          }),
        }),
        
        open_file: tool({
          description: 'Open an existing file in the Notes workspace. Use this when user asks to select, open, view, or show a specific file.',
          inputSchema: z.object({
            path: z.string().describe('Path of the file to open (e.g., "search_campaigns.rb", "example.py")'),
          }),
        }),
        
        create_folder: tool({
          description: 'Create a folder in the Notes workspace. Use this FIRST when creating multiple related files to keep them organized. Call AFTER switch_to_notes.',
          inputSchema: z.object({
            path: z.string().describe('Folder path (e.g., "auth-examples", "api-flows", "error-handling")'),
            description: z.string().describe('Brief description of what this folder will contain'),
          }),
        }),
        
        create_file: tool({
          description: 'Create a new empty file and open it in the editor. Call AFTER checking list_notes for existing similar files. If a similar file exists, use open_file + write_file to UPDATE it instead.',
          inputSchema: z.object({
            path: z.string().describe('File path with extension. Use folders for organization: "folder/file.ext". Extensions: .sh for curl, .py/.ts/.js/.go/.rb for code, .mmd for Mermaid diagrams, .md for docs'),
            description: z.string().describe('Brief description of what this file will contain'),
          }),
        }),
        
        write_file: tool({
          description: 'Write content to a file. Works for both new files (after create_file) and existing files (after open_file). The content will appear in the editor.',
          inputSchema: z.object({
            path: z.string().describe('File path to write to'),
            content: z.string().describe('Complete file content with working code and real example values'),
          }),
        }),
        
        delete_file: tool({
          description: 'Delete a file from the Notes workspace. Use when user wants to remove a file, or when switching implementations (e.g., from Python to Node.js - delete the .py file before creating .js file).',
          inputSchema: z.object({
            path: z.string().describe('Path of the file to delete'),
            reason: z.string().optional().describe('Brief reason for deletion (e.g., "Switching from Python to Node.js")'),
          }),
        }),
        
        delete_all_notes: tool({
          description: 'Delete ALL notes/files in the workspace. Use when user explicitly asks to "delete all", "clear all notes", "remove everything", or "start fresh". IMPORTANT: Always ask for confirmation first before calling this tool. Set confirmed=true only after user confirms.',
          inputSchema: z.object({
            confirmed: z.boolean().describe('Must be true to proceed. Ask user for confirmation first: "Are you sure you want to delete all X notes? This cannot be undone."'),
          }),
        }),
        
        // === API CLIENT ASSISTANCE TOOLS ===
        check_request_validity: tool({
          description: `Check if the current API request is ready to send. Returns validation status for:
- URL path parameters (e.g., {user_id}, {order_id})
- Required query parameters
- Required request body fields
- Authentication configuration

Use this BEFORE sending a request to help users complete missing fields. Returns a detailed breakdown of what's missing and what's configured correctly.`,
          inputSchema: z.object({
            endpointId: z.string().describe('The endpoint ID to validate'),
          }),
        }),
        
        send_request: tool({
          description: `Execute the API request from the playground. Use this when:
- User says "send", "execute", "run", "try it", "make the request", "call the API"
- After helping user fill in all required parameters
- User wants to test the endpoint

Returns the full response including status, headers, body, and timing. If the request fails, includes error details for debugging.`,
          inputSchema: z.object({
            confirmSend: z.boolean().describe('Set to true to confirm sending the request'),
          }),
        }),
      },
      stopWhen: stepCountIs(8),
    })

    return result.toUIMessageStreamResponse()
  } catch (error) {
    console.error('[Chat API] Error:', error)
    
    const errorMessage = error instanceof Error ? error.message : 'Failed to process request'
    
    return new Response(
      JSON.stringify({ error: errorMessage }),
      { status: 500, headers: { 'Content-Type': 'application/json' } }
    )
  }
}
