/**
 * Task Completion Section
 * Provides guidance on when/how to complete tasks, with optional output schema description
 */

import type { z } from 'zod'
import { zodToJsonSchema } from '@alcyone-labs/zod-to-json-schema'

/**
 * Builds the task completion section of the system prompt
 * Includes complete action usage and optional output schema guidance
 *
 * @param outputSchema - Optional Zod schema for output validation
 * @returns Task completion prompt section
 */
export function buildCompletionPrompt(outputSchema?: z.ZodSchema): string {
  let section = '## Task Completion Guidance\n\n'
  section += 'When the task is complete, return a complete action:\n'
  section += '```json\n{ "type": "complete" }\n```\n\n'

  // Only describe output schema if present
  if (outputSchema) {
    section += 'After task completion, the final output will be generated and will need to include:\n'
    section += describeOutputSchema(outputSchema)
    section += '\n\nDuring task execution, focus on gathering all necessary information.'
  } else {
    section += 'This is a side-effect agent (no output generation). Focus on performing the requested actions.'
  }

  return section + '\n'
}

/**
 * Generate natural language description of output schema
 * Provides guidance without enforcing structure during iteration
 *
 * @param schema - Zod schema to describe
 * @returns Natural language description
 */
function describeOutputSchema(schema: z.ZodSchema): string {
  const jsonSchema = zodToJsonSchema(schema as z.ZodSchema<any>, {
    $refStrategy: 'none',
    errorMessages: true
  })

  // Simple description - just show the JSON schema
  // LLM can understand this without needing full enforcement
  return '```json\n' + JSON.stringify(jsonSchema, null, 2) + '\n```'
}
