import fs from 'fs';
import path from 'path';
import { findSquadDir, loadSquad } from '../../../core/squad-loader.js';
/**
 * Find all .pen files in a squad's templates/ directory.
 */
function findPenFiles(squadDir) {
    const templatesDir = path.join(squadDir, 'templates');
    if (!fs.existsSync(templatesDir))
        return [];
    return fs.readdirSync(templatesDir)
        .filter(f => f.endsWith('.pen'))
        .map(f => path.join(templatesDir, f));
}
/**
 * Find all template .md files in a squad's templates/ directory.
 */
function findTemplateMds(squadDir) {
    const templatesDir = path.join(squadDir, 'templates');
    if (!fs.existsSync(templatesDir))
        return [];
    return fs.readdirSync(templatesDir)
        .filter(f => f.startsWith('template-') && f.endsWith('.md'));
}
/**
 * Walk squads directory and find all squads with visual_templates enabled.
 */
function findVisualSquads(squadsDir) {
    const results = [];
    function walk(dir, depth) {
        if (depth > 4)
            return;
        const yamlPath = path.join(dir, 'squad.yaml');
        if (fs.existsSync(yamlPath)) {
            try {
                const config = loadSquad(dir);
                if (config.squad.visualTemplates?.enabled) {
                    results.push(dir);
                }
            }
            catch {
                // Invalid squad — skip
            }
            return;
        }
        let entries;
        try {
            entries = fs.readdirSync(dir, { withFileTypes: true });
        }
        catch {
            return;
        }
        for (const entry of entries) {
            if (!entry.isDirectory())
                continue;
            if (entry.name.startsWith('.') || entry.name.startsWith('_'))
                continue;
            walk(path.join(dir, entry.name), depth + 1);
        }
    }
    walk(squadsDir, 0);
    return results;
}
export async function syncTemplatesCommand(squadFilter) {
    const cwd = process.cwd();
    const squadsDir = path.join(cwd, 'squads');
    if (!fs.existsSync(squadsDir)) {
        console.error('No squads/ directory found. Run `expxagents init` first.');
        process.exit(1);
    }
    let squadDirs;
    if (squadFilter) {
        const dir = findSquadDir(squadsDir, squadFilter);
        if (!dir) {
            console.error(`Squad "${squadFilter}" not found.`);
            process.exit(1);
        }
        squadDirs = [dir];
    }
    else {
        squadDirs = findVisualSquads(squadsDir);
    }
    if (squadDirs.length === 0) {
        console.log('No squads with visual_templates found.');
        console.log('Add `visual_templates: { enabled: true }` to squad.yaml to enable.');
        return;
    }
    console.log(`\nSync Templates — ${squadDirs.length} visual squad(s) found\n`);
    for (const squadDir of squadDirs) {
        const config = loadSquad(squadDir);
        const penFiles = findPenFiles(squadDir);
        const existingMds = findTemplateMds(squadDir);
        const squadName = config.squad.name;
        console.log(`--- ${squadName} (${config.squad.code}) ---`);
        if (penFiles.length === 0) {
            console.log('  No .pen files found in templates/');
            console.log('  Create a .pen file or use Pencil to design templates.');
            // Create templates dir if it doesn't exist
            const templatesDir = path.join(squadDir, 'templates');
            if (!fs.existsSync(templatesDir)) {
                fs.mkdirSync(templatesDir, { recursive: true });
                console.log('  Created templates/ directory');
            }
            console.log('');
            continue;
        }
        console.log(`  .pen files: ${penFiles.map(f => path.basename(f)).join(', ')}`);
        console.log(`  Existing .md templates: ${existingMds.length}`);
        console.log('');
        console.log('  To sync, open the .pen file in Pencil (VSCode) and run:');
        console.log('    1. Open the .pen file in VSCode');
        console.log('    2. Use Claude Code with Pencil MCP to read frames');
        console.log('    3. The sync will generate/update template .md files');
        console.log('');
        // Report existing template .md files
        if (existingMds.length > 0) {
            console.log('  Current templates:');
            for (const md of existingMds) {
                console.log(`    - ${md}`);
            }
            console.log('');
        }
    }
    console.log('Sync complete.');
}
