// tools/scaffold-plugin-handler.ts — Handler for scaffold_plugin tool (SPEC-085 AC-10)
import { mkdir, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { compactResult } from './output-formatter.js';
import { PLANU_VERSION } from '../config/version.js';
function toPluginId(name) {
    return name
        .toLowerCase()
        .replace(/[^a-z0-9-]/g, '-')
        .replace(/-+/g, '-')
        .replace(/^-|-$/g, '');
}
function generateManifest(id, name, description, extensions) {
    const permissions = [];
    for (const ext of extensions) {
        if (ext === 'tools') {
            permissions.push('tools:register');
        }
        if (ext === 'workers') {
            permissions.push('workers:register');
        }
        if (ext === 'analyzers') {
            permissions.push('analyzers:register');
        }
        if (ext === 'templates') {
            permissions.push('templates:register');
        }
    }
    const manifest = {
        id,
        name,
        version: '0.1.0',
        author: 'Your Name',
        description,
        license: 'MIT',
        planuVersion: `>=${PLANU_VERSION}`,
        entryPoint: 'src/index.js',
        permissions,
    };
    return JSON.stringify(manifest, null, 2);
}
function generateEntryPoint(extensions) {
    const lines = [];
    lines.push('// src/index.ts — Plugin entry point');
    lines.push('');
    if (extensions.includes('tools')) {
        lines.push('const exampleTool = {');
        lines.push("  name: 'example-tool',");
        lines.push("  description: 'An example plugin tool',");
        lines.push('  inputSchema: { message: { type: "string" } },');
        lines.push('  handler: async (input) => {');
        lines.push('    return { result: `Hello from plugin: ${input.message}` };');
        lines.push('  },');
        lines.push('};');
        lines.push('');
    }
    if (extensions.includes('workers')) {
        lines.push('const exampleWorker = {');
        lines.push("  name: 'example-worker',");
        lines.push("  trigger: 'manual',");
        lines.push('  handler: async () => {');
        lines.push("    console.log('Worker executed');");
        lines.push('  },');
        lines.push('};');
        lines.push('');
    }
    if (extensions.includes('analyzers')) {
        lines.push('const exampleAnalyzer = {');
        lines.push("  name: 'example-analyzer',");
        lines.push("  filePatterns: ['**/*.ts', '**/*.js'],");
        lines.push('  analyze: async (files) => {');
        lines.push('    return files.map(f => ({');
        lines.push('      file: f,');
        lines.push("      severity: 'info',");
        lines.push("      message: 'File analyzed by plugin',");
        lines.push("      rule: 'example-rule',");
        lines.push('    }));');
        lines.push('  },');
        lines.push('};');
        lines.push('');
    }
    if (extensions.includes('templates')) {
        lines.push('const exampleTemplate = {');
        lines.push("  name: 'example-template',");
        lines.push("  domain: 'general',");
        lines.push("  specTemplate: '# {{name}}\\n\\n## Description\\n\\n{{description}}',");
        lines.push("  technicalTemplate: '# {{name}} — Technical Sheet\\n\\n## Files\\n\\n{{files}}',");
        lines.push('};');
        lines.push('');
    }
    lines.push('export const hooks = {');
    lines.push("  onActivate: async () => { console.log('Plugin activated'); },");
    lines.push("  onDeactivate: async () => { console.log('Plugin deactivated'); },");
    lines.push('};');
    lines.push('');
    // Export arrays
    const exports = [];
    if (extensions.includes('tools')) {
        exports.push('export const tools = [exampleTool];');
    }
    if (extensions.includes('workers')) {
        exports.push('export const workers = [exampleWorker];');
    }
    if (extensions.includes('analyzers')) {
        exports.push('export const analyzers = [exampleAnalyzer];');
    }
    if (extensions.includes('templates')) {
        exports.push('export const templates = [exampleTemplate];');
    }
    lines.push(...exports);
    lines.push('');
    return lines.join('\n');
}
function generateTsConfig() {
    return JSON.stringify({
        compilerOptions: {
            target: 'ES2022',
            module: 'NodeNext',
            moduleResolution: 'NodeNext',
            outDir: './dist',
            rootDir: './src',
            strict: true,
            declaration: true,
            esModuleInterop: true,
        },
        include: ['src'],
    }, null, 2);
}
function generateReadme(name, description) {
    return [
        `# ${name}`,
        '',
        description,
        '',
        '## Installation',
        '',
        '```bash',
        `cp -r ${name}/ planu-plugins/${name}/`,
        '```',
        '',
        '## Development',
        '',
        '```bash',
        'npm install',
        'npm run build',
        'npm test',
        '```',
        '',
    ].join('\n');
}
function generateExampleTest(name) {
    return [
        `// tests/${name}.test.ts`,
        "import { describe, it, expect } from 'vitest';",
        '',
        `describe('${name}', () => {`,
        "  it('should export hooks', async () => {",
        "    const mod = await import('../src/index.js');",
        '    expect(mod.hooks).toBeDefined();',
        '  });',
        '});',
        '',
    ].join('\n');
}
/**
 * Scaffolds a new plugin project directory.
 */
export async function handleScaffoldPlugin(input) {
    const id = toPluginId(input.name);
    const baseDir = input.outputDir ?? process.cwd();
    const pluginDir = join(baseDir, id);
    const files = [];
    // Create directories
    await mkdir(join(pluginDir, 'src'), { recursive: true });
    await mkdir(join(pluginDir, 'tests'), { recursive: true });
    // Write files
    const manifest = generateManifest(id, input.name, input.description, input.extensions);
    await writeFile(join(pluginDir, 'plugin.json'), manifest, 'utf8');
    files.push('plugin.json');
    const entry = generateEntryPoint(input.extensions);
    await writeFile(join(pluginDir, 'src', 'index.ts'), entry, 'utf8');
    files.push('src/index.ts');
    const tsconfig = generateTsConfig();
    await writeFile(join(pluginDir, 'tsconfig.json'), tsconfig, 'utf8');
    files.push('tsconfig.json');
    const readme = generateReadme(input.name, input.description);
    await writeFile(join(pluginDir, 'README.md'), readme, 'utf8');
    files.push('README.md');
    const test = generateExampleTest(id);
    await writeFile(join(pluginDir, 'tests', `${id}.test.ts`), test, 'utf8');
    files.push(`tests/${id}.test.ts`);
    const gitignore = ['node_modules/', 'dist/', '*.js', '!src/**/*.js'].join('\n');
    await writeFile(join(pluginDir, '.gitignore'), gitignore, 'utf8');
    files.push('.gitignore');
    const lines = [
        `**pluginId**: ${id}`,
        `**pluginDir**: ${pluginDir}`,
        `Plugin "${input.name}" scaffolded successfully. Edit src/index.ts to add your logic.`,
        '',
        '## Files Created',
        ...files.map((f) => `- ${f}`),
    ];
    return compactResult(lines.join('\n'));
}
//# sourceMappingURL=scaffold-plugin-handler.js.map