// tools/spec-templates.ts — Handlers for list_templates and apply_template tools.
import { mkdir, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { listTemplates, findTemplateWithCustom, renderTemplate, findMissingRequired, } from '../engine/spec-templates/index.js';
import { t, ti } from '../i18n/index.js';
/**
 * Returns the list of available spec templates, optionally filtered.
 */
export async function handleListTemplates(args) {
    try {
        const { result, warnings } = await listTemplates(args.category, args.search, args.complexityScore);
        const filterText = result.filteredBy !== undefined
            ? ` (${ti('tools.spec_templates.filteredBy', { filter: result.filteredBy })})`
            : '';
        const lines = [
            `# ${t('tools.spec_templates.listTitle')}`,
            '',
            ti('tools.spec_templates.found', {
                count: String(result.total),
                plural: result.total === 1 ? '' : 's',
                filter: filterText,
            }),
            '',
        ];
        if (result.templates.length === 0) {
            lines.push(t('tools.spec_templates.noMatch'));
        }
        else {
            for (const tpl of result.templates) {
                lines.push(`## ${tpl.name} (\`${tpl.id}\`)`);
                lines.push(`- **${t('tools.spec_templates.category')}** ${tpl.category}${tpl.subcategory !== undefined ? ` (${tpl.subcategory})` : ''}`);
                lines.push(`- **${t('tools.spec_templates.complexity')}** ${tpl.complexityScore}`);
                lines.push(`- **${t('tools.spec_templates.criteria')}** ${tpl.criteriaCount}`);
                lines.push(`- **${t('tools.spec_templates.templateDescription')}** ${tpl.description}`);
                lines.push(`- **${t('tools.spec_templates.tags')}** ${tpl.tags.join(', ')}`);
                lines.push(`- **${t('tools.spec_templates.variables')}** ${ti('tools.spec_templates.variablesDetail', { total: String(tpl.variableCount), required: String(tpl.requiredVariableCount) })}`);
                lines.push('');
            }
        }
        if (warnings.length > 0) {
            lines.push(`### ${t('tools.spec_templates.customWarnings')}`);
            for (const w of warnings) {
                lines.push(`- **${w.file}**: ${w.error}`);
            }
            lines.push('');
        }
        lines.push('---');
        lines.push(t('tools.spec_templates.useApply'));
        lines.push(t('tools.spec_templates.customLocation'));
        return {
            content: [{ type: 'text', text: lines.join('\n') }],
        };
    }
    catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        return {
            content: [{ type: 'text', text: ti('tools.spec_templates.listError', { message }) }],
            isError: true,
        };
    }
}
/**
 * Applies a template to create HU.md + FICHA-TECNICA.md + PROGRESS.md.
 */
export async function handleApplyTemplate(args) {
    try {
        const template = await findTemplateWithCustom(args.templateId);
        if (template === undefined) {
            return {
                content: [
                    {
                        type: 'text',
                        text: ti('tools.spec_templates.templateNotFound', { id: args.templateId }),
                    },
                ],
                isError: true,
            };
        }
        const missingRequired = findMissingRequired(template, args.variables);
        if (missingRequired.length > 0) {
            return {
                content: [
                    {
                        type: 'text',
                        text: buildMissingVariablesMessage(missingRequired, template.variables),
                    },
                ],
                isError: true,
            };
        }
        const rendered = renderTemplate(template, args.variables, args.includeCriteria);
        const outputDir = resolveOutputDir(args);
        await mkdir(outputDir, { recursive: true });
        const specPath = join(outputDir, 'HU.md');
        const fichaTecnicaPath = join(outputDir, 'FICHA-TECNICA.md');
        const progressPath = join(outputDir, 'PROGRESS.md');
        await writeFile(specPath, rendered.hu, 'utf-8');
        await writeFile(fichaTecnicaPath, rendered.fichaTecnica, 'utf-8');
        await writeFile(progressPath, rendered.progress, 'utf-8');
        const result = {
            templateId: template.id,
            templateName: template.name,
            complexityScore: template.complexityScore,
            specPath,
            fichaTecnicaPath,
            progressPath,
            variablesApplied: args.variables.length,
            criteriaIncluded: rendered.criteriaIncluded,
            criteriaTotal: rendered.criteriaTotal,
            missingRequired: [],
            warnings: rendered.warnings,
            message: buildSuccessMessage(template.name, outputDir),
        };
        return {
            content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
        };
    }
    catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        return {
            content: [{ type: 'text', text: ti('tools.spec_templates.applyError', { message }) }],
            isError: true,
        };
    }
}
/**
 * Resolves the output directory for the spec files.
 */
function resolveOutputDir(args) {
    if (args.outputDir !== undefined && args.outputDir.trim().length > 0) {
        return args.outputDir.trim();
    }
    // Flat structure — no subcategories. Feature is stored as a tag, not a folder.
    return join(args.projectPath, 'planu', 'specs', slugify(args.templateId));
}
/**
 * Converts a string to a URL-safe slug.
 */
function slugify(text) {
    return text
        .toLowerCase()
        .replace(/[^a-z0-9]+/g, '-')
        .replace(/^-+|-+$/g, '')
        .slice(0, 60);
}
/**
 * Builds a user-friendly error message for missing required variables.
 */
function buildMissingVariablesMessage(missingKeys, definitions) {
    const lines = [t('tools.spec_templates.missingVarsTitle'), ''];
    for (const key of missingKeys) {
        const def = definitions.find((d) => d.key === key);
        if (def !== undefined) {
            lines.push(`- **${def.label}** (key: \`${key}\`): ${def.description}`);
            lines.push(`  ${ti('tools.spec_templates.missingVarExample', { example: def.example })}`);
        }
        else {
            lines.push(`- \`${key}\``);
        }
    }
    lines.push('');
    lines.push(t('tools.spec_templates.missingVarsHint'));
    return lines.join('\n');
}
/**
 * Builds the success message after a template is applied.
 */
function buildSuccessMessage(templateName, outputDir) {
    return [
        ti('tools.spec_templates.applySuccess', { name: templateName }),
        ti('tools.spec_templates.filesCreated', { dir: outputDir }),
        t('tools.spec_templates.nextSteps'),
        t('tools.spec_templates.step1'),
        t('tools.spec_templates.step2'),
        t('tools.spec_templates.step3'),
    ].join('\n');
}
//# sourceMappingURL=spec-templates.js.map