/**
 * Workforce handler group: nexus_work_* tools.
 *
 * Replaces the scattered 24 Synapse + Architects MCP tools with 8 unified tools.
 * Old nexus_synapse_* and nexus_architects_* remain as pass-through aliases until v6.2.
 *
 * Tools:
 *   nexus_work_enqueue   — create a job
 *   nexus_work_claim     — atomically claim a job (or next ready)
 *   nexus_work_progress  — advance wip → review, record tokens
 *   nexus_work_complete  — mark done/failed/blocked
 *   nexus_work_block     — mark blocked with reason
 *   nexus_work_kanban    — get kanban board view
 *   nexus_work_workers   — list/register workers
 *   nexus_work_hire      — register a new worker (alias for workers with auto-name)
 */
import { getWorkforce } from '../../../../workforce/index.js';
import { nxlResult } from '../../../../nxl/index.js';
function text(s) {
    return { content: [{ type: 'text', text: s }] };
}
function json(obj) {
    return { content: [{ type: 'text', text: JSON.stringify(obj, null, 2) }] };
}
export async function handleWorkforceGroup(toolName, hctx, request, _args, _ctx) {
    const ws = hctx.getWorkspace(request.params.arguments ?? {});
    const wf = getWorkforce(ws.repoRoot);
    switch (toolName) {
        case 'nexus_work_enqueue': {
            const title = String(request.params.arguments?.title ?? '');
            if (!title)
                return text('❌ title required');
            const job = wf.enqueueJob({
                title,
                tier: request.params.arguments?.tier ?? 'tactical',
                priority: Number(request.params.arguments?.priority ?? 5),
                parentId: request.params.arguments?.parentId != null ? String(request.params.arguments.parentId) : undefined,
                dependsOn: Array.isArray(request.params.arguments?.dependsOn)
                    ? request.params.arguments.dependsOn.map(String)
                    : [],
                budgetCapUsd: request.params.arguments?.budgetCapUsd != null
                    ? Number(request.params.arguments.budgetCapUsd)
                    : undefined,
                payload: typeof request.params.arguments?.payload === 'object'
                    ? request.params.arguments.payload
                    : {},
                client: String(request.params.arguments?.client ?? hctx.getToolProfile()),
            });
            return text([
                `✅ Job enqueued: ${job.id}`,
                `  Title:  ${job.title}`,
                `  Status: ${job.status}`,
                `  Tier:   ${job.tier}`,
                `  Priority: ${job.priority}`,
            ].join('\n'));
        }
        case 'nexus_work_claim': {
            const workerId = String(request.params.arguments?.workerId ?? '');
            const jobId = request.params.arguments?.jobId ? String(request.params.arguments.jobId) : undefined;
            const leaseMs = request.params.arguments?.leaseMs != null ? Number(request.params.arguments.leaseMs) : undefined;
            if (!workerId)
                return text('❌ workerId required');
            const claim = jobId
                ? wf.claimJob(jobId, workerId, leaseMs)
                : wf.claimNextReady(workerId, leaseMs);
            if (!claim)
                return text(`⚠️ No ready job available (or ${jobId ?? 'next'} already claimed)`);
            const job = wf.getJob(claim.jobId);
            return text([
                `✅ Claimed: ${claim.jobId}`,
                `  Job:      ${job?.title ?? claim.jobId}`,
                `  Worker:   ${workerId}`,
                `  Claim ID: ${claim.id}`,
                `  Expires:  ${new Date(claim.expiresAt).toISOString()}`,
            ].join('\n'));
        }
        case 'nexus_work_progress': {
            const jobId = String(request.params.arguments?.jobId ?? '');
            const workerId = String(request.params.arguments?.workerId ?? '');
            const stage = String(request.params.arguments?.stage ?? 'wip');
            const tokens = request.params.arguments?.tokens != null ? Number(request.params.arguments.tokens) : 0;
            if (!jobId || !workerId)
                return text('❌ jobId + workerId required');
            if (tokens > 0)
                wf.recordTokens(jobId, workerId, tokens);
            if (stage === 'review')
                wf.advanceToReview(jobId, workerId);
            else
                wf.advanceToWip(jobId, workerId);
            const job = wf.getJob(jobId);
            return text(`✅ ${jobId} → ${job?.status ?? stage} (tokens: ${job?.tokensUsed ?? tokens})`);
        }
        case 'nexus_work_complete': {
            const jobId = String(request.params.arguments?.jobId ?? '');
            const workerId = String(request.params.arguments?.workerId ?? '');
            const outcome = String(request.params.arguments?.outcome ?? 'done');
            if (!jobId || !workerId)
                return text('❌ jobId + workerId required');
            const job = outcome === 'done'
                ? wf.completeJob(jobId, workerId)
                : outcome === 'failed'
                    ? wf.failJob(jobId, workerId)
                    : wf.blockJob(jobId, workerId);
            const dag = wf.reconcileDag();
            return text([
                `✅ ${jobId} → ${job?.status ?? outcome}`,
                dag.promoted > 0 ? `  DAG: ${dag.promoted} jobs promoted to ready` : '',
                dag.blocked > 0 ? `  DAG: ${dag.blocked} jobs blocked by failed deps` : '',
            ].filter(Boolean).join('\n'));
        }
        case 'nexus_work_block': {
            const jobId = String(request.params.arguments?.jobId ?? '');
            const workerId = String(request.params.arguments?.workerId ?? '');
            if (!jobId || !workerId)
                return text('❌ jobId + workerId required');
            wf.blockJob(jobId, workerId);
            return text(`⚠️ ${jobId} → blocked`);
        }
        case 'nexus_work_kanban': {
            const client = request.params.arguments?.client ? String(request.params.arguments.client) : undefined;
            const fmt = String(request.params.arguments?.format ?? 'text');
            const board = wf.getKanbanBoard(client);
            if (fmt === 'nxl')
                return nxlResult(board);
            if (fmt === 'json')
                return json(board);
            const lines = [`Kanban Board — ${board.totalJobs} total jobs`];
            for (const [lane, cards] of Object.entries(board.lanes)) {
                if (cards.length === 0)
                    continue;
                lines.push(`\n## ${lane.toUpperCase()} (${cards.length})`);
                for (const c of cards.slice(0, 20)) {
                    lines.push(`  [${c.priority}] ${c.id.slice(0, 8)} — ${c.title} ${c.workerId ? `(→ ${c.workerId.slice(0, 8)})` : ''}`);
                }
                if (cards.length > 20)
                    lines.push(`  ... +${cards.length - 20} more`);
            }
            return text(lines.join('\n'));
        }
        case 'nexus_work_workers': {
            const status = request.params.arguments?.status
                ? String(request.params.arguments.status)
                : undefined;
            const fmt = String(request.params.arguments?.format ?? 'text');
            const workers = wf.listWorkers(status);
            if (workers.length === 0)
                return text('No workers registered.');
            if (fmt === 'nxl')
                return nxlResult(workers);
            if (fmt === 'json')
                return json(workers);
            const lines = [`Workers (${workers.length}):`];
            for (const w of workers) {
                const load = wf.listJobs('wip').filter(j => j.workerId === w.id).length;
                lines.push(`  ${w.id.slice(0, 8)} ${w.name} [${w.status}] client=${w.client} budget=$${w.budgetCapUsd} spent=$${w.spentUsd.toFixed(4)} load=${load} score=${w.score.toFixed(1)}`);
            }
            return text(lines.join('\n'));
        }
        case 'nexus_work_hire': {
            const name = String(request.params.arguments?.name ?? `worker-${Date.now()}`);
            const role = request.params.arguments?.role ? String(request.params.arguments.role) : undefined;
            const client = String(request.params.arguments?.client ?? hctx.getToolProfile());
            const budgetCapUsd = request.params.arguments?.budgetCapUsd != null ? Number(request.params.arguments.budgetCapUsd) : 10;
            const worker = wf.registerWorker({ name, role, client, budgetCapUsd });
            return json({ hired: true, worker });
        }
        default:
            return undefined;
    }
}
