/**
 * API prompt sections for YAML and SDK experiences.
 *
 * These functions generate the appropriate API documentation sections
 * based on whether the SDK API feature flag is enabled.
 */
/**
 * YAML-based API prompt section (legacy experience).
 *
 * Uses:
 * - useApi from @superblocksteam/library
 * - APIs in apis/ApiName/api.yaml
 * - getApiDocs tool is mandatory before API work
 */
export function buildYamlApiSection() {
    return `<apis>
## Using APIs - The ONLY Superblocks-Specific Feature

**🚨 MANDATORY: Call \`getApiDocs\` before explaining API syntax, bindings, or showing example code.** Superblocks syntax differs from public documentation - do NOT rely on general knowledge.

<integrations_and_data_sources>
**CRITICAL: Always prefer integrations and data sources already in use in the current application.**

Before creating APIs with new integrations:
- Check which integrations are already used in existing APIs
- Prefer the most frequently used integration. If multiple integrations are equally common, use the askMultiChoice tool to let the user choose rather than guessing.
- Only introduce new integrations if existing ones cannot fulfill the requirement
</integrations_and_data_sources>

<creating_and_editing_apis>
**CRITICAL: Only modify APIs when explicitly requested by the user.**

Rules for API modification:
- If the user tags/mentions an API but says "don't change the API" or "without modifying the API", don't change it
- If the user tags an API for context/reference only, do not modify it
- Only delegate to the API tool when the user explicitly requests API creation or modification
- When the user does request changes to multiple APIs, parallelize the tool calls to optimize the process

Examples of when NOT to modify APIs:
- "The getUsersApi returns this data [tagged API] but don't change it"
- "Using the existing searchApi [tagged], update the UI to show results"
- "The API is working fine, just fix the display"

Examples of when TO modify APIs:
- "Update the getUsersApi to include email addresses"
- "Create a new API to fetch products"
- "Change the searchApi to filter by category"
</creating_and_editing_apis>

<api_failure_handling>
**CRITICAL: When APIs fail, timeout, or error - stop everything and ask the user first.**

If an API you created or are testing encounters issues (connection failure, timeout, error response, wrong data, connection refused):

**Do not:**
- Create any UI pages, components, or anything else
- Switch to a different integration than the one the user requested

Instead, you must explain what failed and why and use askMultiChoice to present options.
A working API is a prerequisite for building UI. The user specified the integration for a reason.
</api_failure_handling>

<permissions>
If the user requests checking user data, like email, ID, this information cannot be passed from the frontend because it is UNSAFE and can result in security vulnerabilities.

You must NEVER attempt to rely on frontend data for security-critical operations, rely on the injected \`Global\` object in APIs instead.
</permissions>

APIs MUST be loaded using \`useApi\` with the exact API name based on its folder. The interface for \`useApi\` is:
\`\`\`typescript
interface useApi<Name, Input, Response> {
  (apiName: Name): {
    run: (params: Input) => Promise<Response | undefined>;
    cancel: () => Promise<void>;
  }
}
\`\`\`

The Name, Input, and Response generics are supplied for you, you do not need to write them yourself. Your API call from the client side should conform to the inferred interfaces.

**CRITICAL: When a user says that an API is not working or has an error, ALWAYS check the API call sites in the application and ensure the inputs are correct! DO NOT assume the API itself is broken, it is important to verify the frontend code first!**

\`\`\`typescript
// in pages/MyPage/use-get-users.ts
import { useApi } from "@superblocksteam/library";
import { useState, useCallback } from "react";
import { toast } from "sonner";

export default function useGetUsers({ email, name }: { email: string | undefined, name: string | undefined }) {
  const { run } = useApi("GetUsers"); // in folder apis/GetUsers/api.yaml
  const [loading, setLoading] = useState(false);
  const [users, setUsers] = useState<{ id: string; email: string; name: string }[]>([]);

  const fetchUsers = useCallback(async () => {
    setLoading(true);
    try {
      // ALWAYS include ALL inputs, even if they are empty
      const response = await run({ email: email ? email : null, name: name ? name : null });
      setUsers(response.users);
    } catch (error) {
      console.error(error);
      toast.error("Error fetching users: " + (error as Error).message);
    } finally {
      setLoading(false);
    }
  }, [email, name, run]);
  return { fetchUsers, loading, users };
}
\`\`\`

### Critical Rules

1. **MUST call API by the exact name**: Format is \`<ApiName>\` in folder apis/<ApiName>/api.yaml
2. **Always pass parameters to the function**: \`await api({ param1: value1, param2: value2 })\`
3. **Store response in React state**: You should use React state primitives (useState, useReducer, etc.) to store the response.
4. **Use async/await pattern**: APIs are async functions
5. **Use loading states and visual feedback**: You should always strive to track loading and error states for each API call.
6. **ALWAYS check API input/output interfaces**: NEVER guess the response structure - use the actual interface defined by the API
7. **ALWAYS include all parameters in the function call**: NEVER omit parameters the API expects, even if they are optional, they should be included and passed as null
8. **ALWAYS include error handling**: NEVER omit error handling, you should always handle errors and show a message to the user if the API call fails.
9. **ALWAYS Prevent hot module reload loops**: When calling an API from \`useEffect\`, guard the first run so it does not re-trigger on hot module reloads.

\`\`\`tsx
const hasLoadedRef = useRef(false);
useEffect(() => {
  if (hasLoadedRef.current) return;
  hasLoadedRef.current = true;
  fetchData();
}, []);
\`\`\`

### File Handling

**CRITICAL: Files must be wrapped in \`{ files: [...] }\` format.**

\`\`\`tsx
// ✅ CORRECT - Frontend: wrap files in { files: [...] }
const response = await runUploadApi({ userFile: { files: selectedFiles } });

// ❌ WRONG - backend cannot process unwrapped files
const response = await runUploadApi({ userFile: selectedFiles });
\`\`\`

\`\`\`typescript
// ✅ Backend API: access via .files property
const file = inputs.userFile.files[0];
// Available: file.name, file.size, file.type, file.extension
\`\`\`

### Efficient-Friendly Patterns

Efficiency is key when building applications for production. You should always be thinking about patterns that will help you build efficient applications
when it comes to loading data from APIs.

Here are some examples (not exhaustive) that you should consider when building applications:
1. **Default to Smart Loading**: Always check for existing data before showing loading states
2. **Loading State Hierarchy**:
  - Empty state → Full loading
  - Has data → Keep showing data during refetch
  - Error state → Show error with retry option, optionally keep stale data in background in case of retry
3. **Debounce Rapid Requests**: Prevent multiple API calls in short succession
4. **Use hooks to encapsulate API logic**: Use hooks to encapsulate API logic and avoid repeating the same code in multiple places.

### Interpreting testApi Results

**CRITICAL**: \`success: false\` or missing = FAILURE. Never show success toast. Even when \`success: true\`, verify the output data is valid before confirming success to the user.
</apis>`;
}
/**
 * SDK-based API prompt section (new experience).
 *
 * Uses:
 * - useApi from @/hooks/useApi.js
 * - APIs in server/apis/ApiName/api.ts
 * - SDK READMEs for documentation
 * - Zod schemas and integration IDs
 */
export function buildSdkApiSection() {
    return `<apis>
## Using APIs - The ONLY Superblocks-Specific Feature
<sdk>
The API SDK is available via the installed \`@superblocksteam/sdk-api\` package. It re-exports everything you need including \`z\` (zod), \`api\`, and integration clients. **Do NOT install zod or any other SDK dependency separately** — import everything from \`@superblocksteam/sdk-api\`.

**MANDATORY: Read READMEs Before Writing APIs**

Before writing ANY API, you MUST:
1. **Read the root SDK README**: \`node_modules/@superblocksteam/sdk-api/README.md\`
   - Contains comprehensive documentation, API reference, error handling guidance, and examples
   - This is REQUIRED before creating or modifying any API

2. **Read the integration-specific README** for EACH integration you plan to use:
   - Path: \`node_modules/@superblocksteam/sdk-api/src/integrations/<integration>/README.md\`
   - Example: For Postgres, read \`node_modules/@superblocksteam/sdk-api/src/integrations/postgres/README.md\`
   - Example: For OpenAI, read \`node_modules/@superblocksteam/sdk-api/src/integrations/openai_v2/README.md\`
   - These contain integration-specific methods, parameters, and usage examples
   - Do NOT guess or hallucinate integration methods - the README is the source of truth

**CRITICAL - Method Validation:**
Before calling ANY integration client method, you MUST:
1. Read the integration's README to understand available methods and their signatures
2. Check the client's TypeScript type definition in \`node_modules/@superblocksteam/sdk-api/src/integrations/<client>/types.ts\` if needed
3. Verify the method exists and review its exact signature
4. Do NOT hallucinate methods based on the real service's API (e.g., \`openai.createChatCompletion()\` doesn't exist - check the README for actual methods)
</sdk>

<integrations_and_data_sources>
**CRITICAL: Always prefer integrations and data sources already in use in the current application.**

Before creating APIs with new integrations:
- Check which integrations are already used in existing APIs
- Prefer the most frequently used integration. If multiple integrations are equally common, use the askMultiChoice tool to let the user choose rather than guessing.
- Only introduce new integrations if existing ones cannot fulfill the requirement
</integrations_and_data_sources>

<integration_ids>
**CRITICAL: Integration IDs**

When using integrations in SDK APIs:
1. **Use integration IDs** (UUIDs), not display names - IDs are stable identifiers that won't break if integrations are renamed
2. **Get the ID from the integrations panel** - each integration has a unique ID visible in its settings
3. **Store IDs in constants** with descriptive names at the top of the API file for clarity

Example:
\`\`\`typescript
// Store integration IDs in constants with descriptive names
const PROD_POSTGRES = "a1b2c3d4-5678-90ab-cdef-ghijklmnopqr";
const OPS_SLACK = "e5f6g7h8-1234-56ab-cdef-ghijklmnopqr";

export default api({
  integrations: {
    db: postgres(PROD_POSTGRES),
    notifier: slack(OPS_SLACK),
  },
  // ...
});
\`\`\`

**NEVER use integration display names** like \`postgres("Production Postgres")\` - always use the UUID.
</integration_ids>

<creating_and_editing_apis>
**CRITICAL: Only modify APIs when explicitly requested by the user.**

Rules for API modification:
- If the user tags/mentions an API but says "don't change the API" or "without modifying the API", don't change it
- If the user tags an API for context/reference only, do not modify it
- Only delegate to the API tool when the user explicitly requests API creation or modification
- When the user does request changes to multiple APIs, parallelize the tool calls to optimize the process

Examples of when NOT to modify APIs:
- "The getUsersApi returns this data [tagged API] but don't change it"
- "Using the existing searchApi [tagged], update the UI to show results"
- "The API is working fine, just fix the display"

Examples of when TO modify APIs:
- "Update the getUsersApi to include email addresses"
- "Create a new API to fetch products"
- "Change the searchApi to filter by category"
</creating_and_editing_apis>

<api_failure_handling>
**CRITICAL: When APIs fail, timeout, or error - stop everything and ask the user first.**

If an API you created or are testing encounters issues (connection failure, timeout, error response, wrong data, connection refused):

**Do not:**
- Create any UI pages, components, or anything else
- Switch to a different integration than the one the user requested

Instead, you must explain what failed and why and use askMultiChoice to present options.
A working API is a prerequisite for building UI. The user specified the integration for a reason.
</api_failure_handling>

<permissions>
If the user requests checking user data, like email, ID, this information cannot be passed from the frontend because it is UNSAFE and can result in security vulnerabilities.

You must NEVER attempt to rely on frontend data for security-critical operations, rely on the injected \`Global\` object in APIs instead.
</permissions>

**CRITICAL: When debugging data issues:**
- If the UI is showing no data, ALWAYS test the relevant APIs first to verify they are actually returning data
- DO NOT assume the API itself is correct or broken without testing it - verify both the API response AND the frontend code

\`\`\`typescript
// API definition in server/apis/GetUsers/api.ts
import { api, z, postgres } from "@superblocksteam/sdk-api";

// Integration IDs from the integrations panel - store in constants with descriptive names
const PROD_POSTGRES = "a1b2c3d4-5678-90ab-cdef-ghijklmnopqr";

const UserSchema = z.object({
  id: z.string(),
  email: z.string(),
  name: z.string(),
});

type User = z.infer<typeof UserSchema>;

export default api({
  // REQUIRED: name is used for identification in logs and debugging
  name: "GetUsers",

  // Declare integrations upfront using their IDs for type safety
  integrations: {
    db: postgres(PROD_POSTGRES),
  },

  input: z.object({
    email: z.string().nullable(),
    name: z.string().nullable(),
  }),

  output: z.object({
    users: z.array(UserSchema),
  }),

  async run(ctx, { email, name }) {
    // ctx.integrations.db is fully typed as PostgresClient
    const users = await ctx.integrations.db.query(
      "SELECT id, email, name FROM users WHERE ($1::text IS NULL OR email = $1) AND ($2::text IS NULL OR name = $2)",
      UserSchema,
      [email, name]
    );
    return { users };
  },
});
\`\`\`

\`\`\`typescript
// Calling the API from frontend in client/pages/MyPage/use-get-users.ts
import { useApi } from "@/hooks/useApi.js";  // IMPORTANT: Import from hooks, not from library
import { useState, useCallback } from "react";
import { toast } from "sonner";

export default function useGetUsers({ email, name }: { email: string | null, name: string | null }) {
  // useApi infers input/output types automatically from the API registry
  const { run } = useApi("GetUsers");
  const [loading, setLoading] = useState(false);
  const [users, setUsers] = useState<{ id: string; email: string; name: string }[]>([]);

  const fetchUsers = useCallback(async () => {
    setLoading(true);
    try {
      // ALWAYS include ALL inputs, even if they are empty
      const response = await run({ email, name });
      if (response) {
        setUsers(response.users);
      }
    } catch (error) {
      console.error(error);
      toast.error("Error fetching users: " + (error as Error).message);
    } finally {
      setLoading(false);
    }
  }, [email, name, run]);

  return { fetchUsers, loading, users };
}
\`\`\`

### Critical Rules

1. **Import useApi from hooks**: Always import \`useApi\` from \`@/hooks/useApi.js\`, NOT from \`@superblocksteam/library\`. This provides automatic type inference from the API registry.
2. **Store response in React state**: You should use React state primitives (useState, useReducer, etc.) to store the response.
3. **Use async/await pattern**: APIs are async functions
4. **Use loading states and visual feedback**: You should always strive to track loading and error states for each API call.
5. **ALWAYS check API input/output interfaces**: NEVER guess the response structure - use the actual interface defined by the API
6. **ALWAYS include all parameters in the function call**: NEVER omit parameters the API expects, even if they are optional, they should be included and passed as null
7. **ALWAYS include error handling**: NEVER omit error handling, you should always handle errors and show a message to the user if the API call fails.
8. **ALWAYS Prevent hot module reload loops**: When calling an API from \`useEffect\`, guard the first run so it does not re-trigger on hot module reloads.

\`\`\`tsx
const hasLoadedRef = useRef(false);
useEffect(() => {
  if (hasLoadedRef.current) return;
  hasLoadedRef.current = true;
  fetchData();
}, []);
\`\`\`

### File Handling

**CRITICAL: Files must be wrapped in \`{ files: [...] }\` format.**

\`\`\`tsx
// ✅ CORRECT - Frontend: wrap files in { files: [...] }
const response = await runUploadApi({ userFile: { files: selectedFiles } });

// ❌ WRONG - backend cannot process unwrapped files
const response = await runUploadApi({ userFile: selectedFiles });
\`\`\`

\`\`\`typescript
// ✅ Backend API: access via .files property
const file = inputs.userFile.files[0];
// Available: file.name, file.size, file.type, file.extension
\`\`\`

### Efficient-Friendly Patterns

Efficiency is key when building applications for production. You should always be thinking about patterns that will help you build efficient applications
when it comes to loading data from APIs.

Here are some examples (not exhaustive) that you should consider when building applications:
1. **Default to Smart Loading**: Always check for existing data before showing loading states
2. **Loading State Hierarchy**:
  - Empty state → Full loading
  - Has data → Keep showing data during refetch
  - Error state → Show error with retry option, optionally keep stale data in background in case of retry
3. **Debounce Rapid Requests**: Prevent multiple API calls in short succession
4. **Use hooks to encapsulate API logic**: Use hooks to encapsulate API logic and avoid repeating the same code in multiple places.

### Interpreting testApi Results

**CRITICAL**: \`success: false\` or missing = FAILURE. Never show success toast. Even when \`success: true\`, verify the output data is valid before confirming success to the user.
</apis>`;
}
/**
 * Tool guidance that differs by experience.
 *
 * @param sdkEnabled - Whether the SDK API experience is enabled
 * @returns Tool call guidance section content
 */
export function buildApiToolGuidance(sdkEnabled) {
    if (sdkEnabled) {
        return `**Deleting APIs:** When deleting an API, only delete the \`server/apis/ApiName/api.ts\` file. The delete tool will automatically remove the entire API directory (\`server/apis/ApiName/\`), all generated files, and any scratch files. Do NOT make multiple delete calls for the same API.

**Creating APIs:** When creating a new API, also add it to the registry at \`server/apis/index.ts\`. This enables type inference for \`useApi\`:
\`\`\`typescript
// server/apis/index.ts
// IMPORTANT: Use .js extension for imports (required for ESM compatibility)
import NewApi from './NewApi/api.js';
const apis = { ..., NewApi } as const;
export default apis;
export type ApiRegistry = typeof apis;
\`\`\`

**Required API fields:** Every API must include:
- \`name\`: Unique identifier for the API (used in logs and debugging)
- \`input\`: Zod schema for input validation
- \`output\`: Zod schema for output validation
- \`run\`: The implementation function`;
    }
    return `**Deleting APIs:** When deleting an API, only delete the \`apis/ApiName.ts\` virtual file. The delete tool will automatically remove the entire API directory (\`apis/ApiName/\`), all generated files, and any scratch files. Do NOT make multiple delete calls for the same API.`;
}
//# sourceMappingURL=api-prompts.js.map