import fs from 'node:fs';
import path from 'node:path';
export async function ingestCommand(targetPath, options) {
    const serverUrl = process.env.EXPX_SERVER_URL ?? `http://localhost:${process.env.PORT ?? '3001'}`;
    const apiKey = process.env.EXPX_API_KEY ?? '';
    const resolved = path.resolve(targetPath);
    if (!fs.existsSync(resolved)) {
        console.error(`Path not found: ${resolved}`);
        process.exit(1);
    }
    const files = fs.statSync(resolved).isDirectory()
        ? walkFiles(resolved)
        : [resolved];
    console.log(`Ingesting ${files.length} file(s)...`);
    let success = 0;
    let skipped = 0;
    let failed = 0;
    for (const file of files) {
        try {
            const content = fs.readFileSync(file, 'utf-8');
            const title = path.basename(file);
            const tags = options.tags?.split(',').map((t) => t.trim()) ?? undefined;
            const response = await fetch(`${serverUrl}/api/knowledge/ingest-text`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    Authorization: `Bearer ${apiKey}`,
                },
                body: JSON.stringify({ content, title, squad_code: options.squad, tags }),
            });
            if (!response.ok) {
                console.error(`  FAIL ${file}: ${response.status}`);
                failed++;
                continue;
            }
            const result = (await response.json());
            if (result.skipped) {
                console.log(`  SKIP ${file} (unchanged)`);
                skipped++;
            }
            else {
                console.log(`  OK   ${file} (${result.chunks_count} chunks)`);
                success++;
            }
        }
        catch (err) {
            console.error(`  FAIL ${file}: ${err.message}`);
            failed++;
        }
    }
    console.log(`\nDone: ${success} ingested, ${skipped} skipped, ${failed} failed`);
    if (options.watch) {
        console.log(`\nWatching ${resolved} for changes... (Ctrl+C to stop)`);
        const chokidar = await import('chokidar');
        const watcher = chokidar.watch(resolved, { ignoreInitial: true, depth: 5 });
        watcher.on('add', (fp) => handleWatchEvent(fp, serverUrl, apiKey, options));
        watcher.on('change', (fp) => handleWatchEvent(fp, serverUrl, apiKey, options));
        process.on('SIGINT', () => { watcher.close(); process.exit(0); });
        await new Promise(() => { });
    }
}
async function handleWatchEvent(file, serverUrl, apiKey, options) {
    const ext = path.extname(file).toLowerCase();
    const SUPPORTED = new Set(['.md', '.txt', '.json', '.yaml', '.yml']);
    if (!SUPPORTED.has(ext))
        return;
    try {
        const content = fs.readFileSync(file, 'utf-8');
        const response = await fetch(`${serverUrl}/api/knowledge/ingest-text`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${apiKey}` },
            body: JSON.stringify({ content, title: path.basename(file), squad_code: options.squad }),
        });
        const result = (await response.json());
        console.log(`  ${result.skipped ? 'SKIP' : 'OK'}   ${file}`);
    }
    catch (err) {
        console.error(`  FAIL ${file}: ${err.message}`);
    }
}
function walkFiles(dir) {
    const SUPPORTED = new Set(['.md', '.txt', '.json', '.yaml', '.yml']);
    const results = [];
    for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
        if (entry.name.startsWith('.') || entry.name.startsWith('_'))
            continue;
        const full = path.join(dir, entry.name);
        if (entry.isDirectory()) {
            results.push(...walkFiles(full));
        }
        else if (SUPPORTED.has(path.extname(entry.name).toLowerCase())) {
            results.push(full);
        }
    }
    return results;
}
