import fs from 'fs';
import path from 'path';
import yaml from 'js-yaml';
import { loadSkills } from '../../../core/skills-loader.js';
import { readState } from '../../../core/state-manager.js';
function walkSquads(squadsDir) {
    if (!fs.existsSync(squadsDir))
        return [];
    const entries = [];
    function walk(dir) {
        let dirEntries;
        try {
            dirEntries = fs.readdirSync(dir, { withFileTypes: true });
        }
        catch {
            return;
        }
        for (const entry of dirEntries) {
            if (!entry.isDirectory())
                continue;
            if (entry.name.startsWith('.') || entry.name.startsWith('_'))
                continue;
            const fullPath = path.join(dir, entry.name);
            const yamlPath = path.join(fullPath, 'squad.yaml');
            if (fs.existsSync(yamlPath)) {
                try {
                    const raw = fs.readFileSync(yamlPath, 'utf-8');
                    const parsed = yaml.load(raw);
                    const s = parsed?.squad;
                    if (s) {
                        const state = readState(fullPath);
                        entries.push({
                            code: s.code ?? entry.name,
                            name: s.name ?? entry.name,
                            description: s.description ?? '',
                            setor: s.setor,
                            grupo: s.grupo,
                            sessao: s.sessao,
                            agentCount: Array.isArray(s.agents) ? s.agents.length : 0,
                            stepCount: Array.isArray(s.pipeline?.steps) ? s.pipeline.steps.length : 0,
                            status: state?.status ?? 'idle',
                        });
                    }
                }
                catch (err) {
                    entries.push({
                        code: entry.name,
                        name: entry.name,
                        description: `error loading: ${err.message}`,
                        agentCount: 0,
                        stepCount: 0,
                        status: 'error',
                    });
                }
                // Do NOT recurse into squad directories
            }
            else {
                walk(fullPath);
            }
        }
    }
    walk(squadsDir);
    return entries;
}
function capitalize(s) {
    return s
        .split('-')
        .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
        .join(' ');
}
export async function listCommand() {
    const cwd = process.cwd();
    const squadsDir = path.join(cwd, 'squads');
    const skillsDir = path.join(cwd, 'skills');
    console.log('Squads:');
    console.log('-------');
    if (fs.existsSync(squadsDir)) {
        const allSquads = walkSquads(squadsDir);
        if (allSquads.length === 0) {
            console.log('  No squads found. Run `expxagents create` to create one.\n');
        }
        else {
            const hierarchical = allSquads
                .filter((s) => s.setor)
                .sort((a, b) => {
                const ak = `${a.setor}/${a.grupo}/${a.sessao}/${a.code}`;
                const bk = `${b.setor}/${b.grupo}/${b.sessao}/${b.code}`;
                return ak.localeCompare(bk);
            });
            const flat = allSquads.filter((s) => !s.setor);
            // Render hierarchical squads
            let lastHeader = '';
            for (const s of hierarchical) {
                const header = `${capitalize(s.setor)} > ${capitalize(s.grupo ?? '')} > ${capitalize(s.sessao ?? '')}`;
                if (header !== lastHeader) {
                    console.log(`\n  ${header}`);
                    lastHeader = header;
                }
                console.log(`    ${s.name} (${s.code})`);
                console.log(`      Status: ${s.status} | Agents: ${s.agentCount} | Steps: ${s.stepCount}`);
                console.log(`      ${s.description}`);
            }
            // Render flat (legacy) squads
            if (flat.length > 0) {
                console.log('\n  [sem hierarquia]');
                for (const s of flat) {
                    console.log(`    ${s.name} (${s.code})`);
                    console.log(`      Status: ${s.status} | Agents: ${s.agentCount} | Steps: ${s.stepCount}`);
                    console.log(`      ${s.description}`);
                }
            }
            console.log('');
        }
    }
    else {
        console.log('  No squads directory. Run `expxagents init` first.\n');
    }
    // List skills (unchanged)
    console.log('Skills:');
    console.log('-------');
    const skills = loadSkills(skillsDir);
    if (skills.length === 0) {
        console.log('  No skills installed. Run `expxagents install <skill>` to add one.');
    }
    else {
        for (const skill of skills) {
            console.log(`  ${skill.name} (${skill.type}) — ${skill.description}`);
        }
    }
}
