/**
 * Team Template Utilities
 *
 * Loads pre-built team templates from config/templates/ so users can
 * quickly bootstrap a working multi-agent team during onboarding.
 *
 * @module cli/utils/templates
 */
import path from 'path';
import { readFileSync, readdirSync, existsSync, statSync } from 'fs';
// ========================= Internals =========================
/**
 * Resolves the absolute path to the config/templates/ directory.
 *
 * Walks up from the CLI entry point (process.argv[1]) to find the project root
 * containing config/templates/. Falls back to process.cwd() if not found
 * (e.g. in test environments).
 *
 * @returns Absolute path to templates directory
 */
export function getTemplatesDir() {
    // Walk up from the CLI entry script to find config/templates/
    let dir = process.argv[1] ? path.dirname(path.resolve(process.argv[1])) : process.cwd();
    for (let i = 0; i < 10; i++) {
        const candidate = path.join(dir, 'config', 'templates');
        if (existsSync(candidate)) {
            return candidate;
        }
        const parent = path.dirname(dir);
        if (parent === dir)
            break;
        dir = parent;
    }
    // Fallback: relative to CWD (for development and tests)
    return path.join(process.cwd(), 'config', 'templates');
}
// ========================= Public API =========================
/**
 * Lists all available team templates.
 *
 * Reads templates from config/templates/ in both formats:
 * - New format: subdirectory/template.json with roles[] and verificationPipeline
 * - Legacy format: flat JSON files with members[] at root level
 *
 * New-format templates are converted to the CLI TeamTemplate interface
 * by mapping roles to members.
 *
 * @returns Array of team templates sorted by name
 *
 * @example
 * ```typescript
 * const templates = listTemplates();
 * templates.forEach(t => console.log(`${t.name}: ${t.description}`));
 * ```
 */
export function listTemplates() {
    const templatesDir = getTemplatesDir();
    let entries;
    try {
        entries = readdirSync(templatesDir);
    }
    catch {
        return [];
    }
    const templates = [];
    const seenIds = new Set();
    // First pass: load new-format templates from subdirectories
    for (const entry of entries) {
        const fullPath = path.join(templatesDir, entry);
        try {
            const stat = statSync(fullPath);
            if (stat.isDirectory()) {
                const templateJsonPath = path.join(fullPath, 'template.json');
                if (existsSync(templateJsonPath)) {
                    const content = readFileSync(templateJsonPath, 'utf-8');
                    const parsed = JSON.parse(content);
                    // New format: has roles[] array and verificationPipeline
                    if (parsed.id && parsed.name && Array.isArray(parsed.roles) && parsed.roles.length > 0) {
                        const converted = convertNewFormatTemplate(parsed);
                        if (converted) {
                            templates.push(converted);
                            seenIds.add(converted.id);
                        }
                    }
                }
            }
        }
        catch {
            // Skip invalid directories
        }
    }
    // Second pass: load legacy flat JSON templates (skip if ID already seen)
    const jsonFiles = entries.filter(f => f.endsWith('.json') && !f.startsWith('.'));
    for (const file of jsonFiles) {
        try {
            const content = readFileSync(path.join(templatesDir, file), 'utf-8');
            const parsed = JSON.parse(content);
            if (parsed.id && parsed.name && Array.isArray(parsed.members) && !seenIds.has(parsed.id)) {
                templates.push(parsed);
                seenIds.add(parsed.id);
            }
        }
        catch {
            // Skip malformed template files
        }
    }
    return templates.sort((a, b) => a.name.localeCompare(b.name));
}
/**
 * Converts a new-format template (with roles[]) to CLI TeamTemplate (with members[]).
 *
 * Maps each role to one or more TemplateMember entries based on the role's count.
 *
 * @param data - Raw parsed template.json data
 * @returns Converted TeamTemplate, or null if conversion fails
 */
function convertNewFormatTemplate(data) {
    try {
        const roles = data.roles;
        const members = [];
        for (const role of roles) {
            for (let i = 0; i < (role.count || 1); i++) {
                const suffix = role.count > 1 ? ` ${i + 1}` : '';
                members.push({
                    name: `${role.defaultName}${suffix}`,
                    role: role.role,
                    systemPrompt: role.promptAdditions ?? `You are a ${role.label}.`,
                    skillOverrides: role.defaultSkills,
                    excludedRoleSkills: role.excludedSkills,
                });
            }
        }
        return {
            id: data.id,
            name: data.name,
            description: data.description ?? '',
            members,
        };
    }
    catch {
        return null;
    }
}
/**
 * Gets a specific team template by ID.
 *
 * @param id - The template identifier (e.g. "web-dev-team")
 * @returns The matching template, or undefined if not found
 *
 * @example
 * ```typescript
 * const template = getTemplate('startup-team');
 * if (template) {
 *   console.log(`Found: ${template.name} with ${template.members.length} members`);
 * }
 * ```
 */
export function getTemplate(id) {
    return listTemplates().find(t => t.id === id);
}
//# sourceMappingURL=templates.js.map