import type { ToolDefinition } from '../types.js';

/**
 * Generates a single tool file with Zod schema
 */
export function generateToolFile(tool: ToolDefinition): string {
  const { name, description } = tool;

  // Generate schema name (capitalize first letter + "Schema")
  const schemaName = `${name.charAt(0).toUpperCase()}${name.slice(1)}Schema`;

  // Generate simple Zod schema (can be enhanced in advanced mode)
  const schemaContent = generateSimpleSchema();

  return `import { tool } from 'ai';
import { z } from 'zod';

const ${schemaName} = z.object({
${schemaContent}
});

export const ${name} = tool({
  description: '${description}',
  inputSchema: ${schemaName},
  async execute(input: z.infer<typeof ${schemaName}>) {
    // Defensive check: Validate required parameters
    if (!input.text || input.text.trim().length === 0) {
      return {
        success: false,
        error: 'Missing required parameter: text',
        message: 'The "text" parameter is required and cannot be empty.',
      };
    }

    // TODO: Implement the tool logic here
    console.log('${name} called with:', input);

    return {
      success: true,
      message: 'Tool executed successfully. Replace this with your implementation.',
      input,
    };
  },
});
`;
}

/**
 * Generates a simple Zod schema with example fields
 */
function generateSimpleSchema(): string {
  return `  text: z.string().min(1, 'Text cannot be empty').describe('The input text to process.'),
  options: z.object({
    language: z.string().default('en').describe('Language code (e.g., en, es, fr).'),
    maxLength: z.number().int().positive().default(100).describe('Maximum length of output.'),
  }).default({ language: 'en', maxLength: 100 }).describe('Optional configuration.'),`;
}

/**
 * Generates the main index.ts file that re-exports all tools
 */
export function generateIndexFile(tools: ToolDefinition[]): string {
  const exports = tools
    .map((tool) => `export { ${tool.name} } from './tools/${tool.name}.js';`)
    .join('\n');

  return `/**
 * TPMJS Tool Package
 * Auto-generated by @tpmjs/create-basic-tools
 */

${exports}
`;
}
