export async function knowledgeCommand(action, args, options) {
    const serverUrl = process.env.EXPX_SERVER_URL ?? `http://localhost:${process.env.PORT ?? '3001'}`;
    const apiKey = process.env.EXPX_API_KEY ?? '';
    const headers = { Authorization: `Bearer ${apiKey}` };
    switch (action) {
        case 'search': {
            const query = args.join(' ');
            if (!query) {
                console.error('Usage: expxagents knowledge search "query"');
                process.exit(1);
            }
            const params = new URLSearchParams({ q: query, mode: options.mode ?? 'auto' });
            if (options.squad)
                params.set('squad', options.squad);
            const res = await fetch(`${serverUrl}/api/knowledge/query?${params}`, { headers });
            const data = (await res.json());
            for (const r of data.results ?? []) {
                console.log(`[${r.score.toFixed(3)}] ${r.source.document_title}`);
                console.log(`  ${r.content.slice(0, 200)}${r.content.length > 200 ? '...' : ''}`);
                console.log();
            }
            if (!data.results?.length)
                console.log('No results found.');
            break;
        }
        case 'stats': {
            const res = await fetch(`${serverUrl}/api/knowledge/stats`, { headers });
            const stats = (await res.json());
            console.log(`Documents: ${stats.documents}`);
            console.log(`Chunks:    ${stats.chunks}`);
            console.log(`Entities:  ${stats.entities}`);
            console.log(`Relations: ${stats.relations}`);
            break;
        }
        case 'list': {
            const res = await fetch(`${serverUrl}/api/knowledge/documents`, { headers });
            const data = (await res.json());
            for (const doc of data.documents ?? []) {
                console.log(`${doc.id}  ${doc.title}  [${doc.source_type}]  ${doc.ingested_at}`);
            }
            if (!data.documents?.length)
                console.log('No documents found.');
            break;
        }
        case 'delete': {
            const id = args[0];
            if (!id) {
                console.error('Usage: expxagents knowledge delete <doc-id>');
                process.exit(1);
            }
            const res = await fetch(`${serverUrl}/api/knowledge/documents/${id}`, { method: 'DELETE', headers });
            if (res.ok)
                console.log(`Deleted document ${id}`);
            else
                console.error(`Failed to delete: ${res.status}`);
            break;
        }
        case 'rebuild': {
            console.log('Rebuilding knowledge base (re-extracting failed documents)...');
            const res = await fetch(`${serverUrl}/api/knowledge/documents`, { headers });
            const data = (await res.json());
            const failed = (data.documents ?? []).filter((d) => d.extraction_status === 'failed');
            console.log(`Found ${failed.length} failed documents to re-process.`);
            for (const doc of failed) {
                if (doc.source_path) {
                    await fetch(`${serverUrl}/api/knowledge/ingest-text`, {
                        method: 'POST',
                        headers: { ...headers, 'Content-Type': 'application/json' },
                        body: JSON.stringify({ content: '(rebuild)', title: doc.title }),
                    });
                }
            }
            console.log('Rebuild complete.');
            break;
        }
        default:
            console.error(`Unknown action: ${action}. Available: search, stats, list, delete, rebuild`);
            process.exit(1);
    }
}
