import { spawn } from 'child_process';
import path from 'path';
import fs from 'fs';
import { getCoreAsset } from '../utils/config.js';
export async function createCommand(description) {
    const cwd = process.cwd();
    const architectPath = getCoreAsset('solution-architect.agent.md');
    const companyPath = path.join(cwd, '_expxagents', '_memory', 'company.md');
    const prefsPath = path.join(cwd, '_expxagents', '_memory', 'preferences.md');
    if (!fs.existsSync(architectPath)) {
        console.error('Architect prompt not found. Package may be corrupted — reinstall expxagents.');
        process.exit(1);
    }
    const architectPrompt = fs.readFileSync(architectPath, 'utf-8');
    // Load context
    let context = '';
    if (fs.existsSync(companyPath)) {
        const company = fs.readFileSync(companyPath, 'utf-8');
        if (!company.includes('NOT CONFIGURED')) {
            context += '\n## Company Context\n\n' + company;
        }
    }
    if (fs.existsSync(prefsPath)) {
        context += '\n## User Preferences\n\n' + fs.readFileSync(prefsPath, 'utf-8');
    }
    // Load Insight Hunter from package assets
    const hunterPath = getCoreAsset('prompts/insight-hunter.prompt.md');
    if (fs.existsSync(hunterPath)) {
        context += '\n## Insight Hunter Instructions\n\n' + fs.readFileSync(hunterPath, 'utf-8');
    }
    const fullPrompt = architectPrompt + context + (description ? `\n\n## User Request\n\n${description}` : '');
    const squadsDir = path.join(cwd, 'squads');
    if (!fs.existsSync(squadsDir)) {
        fs.mkdirSync(squadsDir, { recursive: true });
    }
    console.log('Starting Solution Architect...\n');
    // Run from project root so the architect can create squads/<setor>/<grupo>/<sessao>/<code>/
    // with the correct hierarchy without path duplication.
    const child = spawn('claude', ['-p', fullPrompt], {
        cwd,
        stdio: 'inherit',
    });
    child.on('error', (err) => {
        console.error(`Failed to start Claude Code: ${err.message}`);
        process.exit(1);
    });
    child.on('exit', (code) => {
        if (code === 0) {
            console.log('\nSquad created! Run `expxagents list` to see it.');
        }
        else {
            console.error(`\nArchitect exited with code ${code}`);
        }
    });
}
