#!/usr/bin/env node
/**
 * Build script to generate TypeScript from prompt markdown files.
 *
 * Reads all .md files from src/prompts/ and generates src/generated/prompts.ts
 * with the content as exported string constants.
 *
 * This allows prompts to be:
 * - Edited as readable markdown files
 * - Imported as regular TypeScript constants (no runtime file I/O)
 * - Used consistently in both renderer and main process
 */

import * as fs from 'fs';
import * as path from 'path';
import { fileURLToPath } from 'url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const rootDir = path.resolve(__dirname, '..');
const promptsDir = path.join(rootDir, 'src/prompts');
const outputDir = path.join(rootDir, 'src/generated');
const outputFile = path.join(outputDir, 'prompts.ts');

/**
 * Convert a filename like "wizard-system.md" to a camelCase variable name
 * like "wizardSystemPrompt"
 */
function filenameToVarName(filename) {
  const base = filename.replace(/\.md$/, '');
  const parts = base.split('-');
  const camelCase = parts
    .map((part, i) => (i === 0 ? part : part.charAt(0).toUpperCase() + part.slice(1)))
    .join('');
  // Only add "Prompt" suffix if the name doesn't already end with it
  if (camelCase.toLowerCase().endsWith('prompt')) {
    return camelCase;
  }
  return camelCase + 'Prompt';
}

/**
 * Escape backticks and ${} in template literal content
 */
function escapeTemplateString(content) {
  return content
    .replace(/\\/g, '\\\\')
    .replace(/`/g, '\\`')
    .replace(/\$\{/g, '\\${');
}

async function generate() {
  console.log('Generating prompts from markdown files...');

  // Ensure output directory exists
  if (!fs.existsSync(outputDir)) {
    fs.mkdirSync(outputDir, { recursive: true });
  }

  // Find all .md files in prompts directory (not in subdirectories)
  const files = fs.readdirSync(promptsDir).filter((f) => f.endsWith('.md'));

  if (files.length === 0) {
    console.error('No .md files found in', promptsDir);
    process.exit(1);
  }

  // Build the output
  const exports = [];
  const lines = [
    '/**',
    ' * AUTO-GENERATED FILE - DO NOT EDIT DIRECTLY',
    ' *',
    ' * This file is generated by scripts/generate-prompts.mjs',
    ' * Edit the source .md files in src/prompts/ instead.',
    ' *',
    ` * Generated: ${new Date().toISOString()}`,
    ' */',
    '',
  ];

  for (const file of files.sort()) {
    const filePath = path.join(promptsDir, file);
    const content = fs.readFileSync(filePath, 'utf8');
    const varName = filenameToVarName(file);

    lines.push(`export const ${varName} = \`${escapeTemplateString(content)}\`;`);
    lines.push('');
    exports.push(varName);
  }

  // Write the file
  fs.writeFileSync(outputFile, lines.join('\n'));

  console.log(`✓ Generated ${outputFile}`);
  console.log(`  ${exports.length} prompts: ${exports.join(', ')}`);
}

generate().catch((error) => {
  console.error('Generation failed:', error);
  process.exit(1);
});
