"use strict";
/**
 * End-to-end process runner for Long Tail examples.
 *
 * Walks Process 3 ("Wrong Language → Durable MCP") through the full
 * escalation chain and MCP triage cycle:
 *
 *   1. Wait for server + seeded escalation
 *   2. Reviewer claims → escalates to admin
 *   3. Admin claims → escalates to engineer
 *   4. Engineer claims → resolves with needsTriage, describes: "Content is in Spanish"
 *   5. LLM-driven MCP triage diagnoses, translates, re-runs workflow, notifies engineering
 *   6. Verify: original workflow completed, engineering escalation created
 *
 * Usage:
 *   npx tsx scripts/process.ts
 *   npx tsx scripts/process.ts --base http://localhost:3000
 */
Object.defineProperty(exports, "__esModule", { value: true });
const process_helpers_1 = require("./process-helpers");
if (process.argv.includes('--base')) {
    (0, process_helpers_1.setBase)(process.argv[process.argv.indexOf('--base') + 1]);
}
// ── Main ────────────────────────────────────────────────────────────────────
async function run() {
    const BASE = (0, process_helpers_1.getBase)();
    console.log('\n  Long Tail — Process Runner');
    console.log('  ═════════════════════════════════════════════════════════════\n');
    console.log(`  Server: ${BASE}`);
    // ── 0. Wait for server ──────────────────────────────────────────────────
    (0, process_helpers_1.header)('Waiting for server');
    await (0, process_helpers_1.poll)('server ready', async () => {
        try {
            const res = await fetch(`${BASE}/health`);
            return res.ok ? true : null;
        }
        catch {
            return null;
        }
    }, 60_000, 2_000);
    (0, process_helpers_1.log)('system', 'Server is up');
    // ── 1. Login as all users ───────────────────────────────────────────────
    (0, process_helpers_1.header)('Authentication');
    const reviewerToken = await (0, process_helpers_1.login)('reviewer', 'l0ngt@1l');
    (0, process_helpers_1.log)('reviewer', 'Logged in');
    const adminToken = await (0, process_helpers_1.login)('admin', 'l0ngt@1l');
    (0, process_helpers_1.log)('admin', 'Logged in');
    const engineerToken = await (0, process_helpers_1.login)('engineer', 'l0ngt@1l');
    (0, process_helpers_1.log)('engineer', 'Logged in');
    // ── 2. Wait for Process 3 escalation to appear ──────────────────────────
    (0, process_helpers_1.header)('Process 3 — Wrong Language');
    (0, process_helpers_1.log)('system', 'Waiting for escalation (wrong_language content) ...');
    const escalation = await (0, process_helpers_1.poll)('process-3 escalation', async () => {
        const { escalations } = await (0, process_helpers_1.api)('GET', '/escalations/available?role=reviewer&limit=50', reviewerToken);
        // Find the one with wrong_language flag in the escalation payload
        return escalations.find((e) => {
            if (!e.escalation_payload)
                return false;
            try {
                const payload = typeof e.escalation_payload === 'string'
                    ? JSON.parse(e.escalation_payload)
                    : e.escalation_payload;
                return payload?.analysis?.flags?.includes('wrong_language');
            }
            catch {
                return false;
            }
        }) ?? null;
    }, 30_000);
    const originId = escalation.origin_id;
    (0, process_helpers_1.log)('system', `Found escalation ${escalation.id.slice(0, 8)}... (origin: ${originId?.slice(0, 30)}...)`);
    // ── 3. Reviewer: claim → escalate to admin ──────────────────────────────
    (0, process_helpers_1.header)('Step 1 — Reviewer');
    await (0, process_helpers_1.api)('POST', `/escalations/${escalation.id}/claim`, reviewerToken);
    (0, process_helpers_1.log)('reviewer', 'Claimed escalation');
    // Read the escalation details
    const detail = await (0, process_helpers_1.api)('GET', `/escalations/${escalation.id}`, reviewerToken);
    const payloadData = detail.escalation_payload
        ? (typeof detail.escalation_payload === 'string' ? JSON.parse(detail.escalation_payload) : detail.escalation_payload)
        : {};
    (0, process_helpers_1.log)('reviewer', `Content: "${(payloadData.content || '').slice(0, 50)}..."`);
    (0, process_helpers_1.log)('reviewer', `Flags: ${payloadData.analysis?.flags?.join(', ') || 'none'}`);
    (0, process_helpers_1.log)('reviewer', 'This is a language issue — outside my role. Escalating to admin.');
    await (0, process_helpers_1.api)('PATCH', `/escalations/${escalation.id}/escalate`, reviewerToken, {
        targetRole: 'admin',
    });
    (0, process_helpers_1.log)('reviewer', 'Escalated → admin');
    // ── 4. Admin: claim → escalate to engineer ──────────────────────────────
    (0, process_helpers_1.header)('Step 2 — Admin');
    // Poll for the escalation to appear in admin's queue
    const adminEsc = await (0, process_helpers_1.poll)('admin escalation', async () => {
        const { escalations } = await (0, process_helpers_1.api)('GET', '/escalations/available?role=admin&limit=50', adminToken);
        return escalations.find((e) => e.id === escalation.id) ?? null;
    });
    await (0, process_helpers_1.api)('POST', `/escalations/${adminEsc.id}/claim`, adminToken);
    (0, process_helpers_1.log)('admin', 'Claimed escalation');
    (0, process_helpers_1.log)('admin', 'Content is in Spanish — needs technical fix. Escalating to engineer.');
    await (0, process_helpers_1.api)('PATCH', `/escalations/${adminEsc.id}/escalate`, adminToken, {
        targetRole: 'engineer',
    });
    (0, process_helpers_1.log)('admin', 'Escalated → engineer');
    // ── 5. Engineer: claim → resolve with needsTriage ───────────────────────
    (0, process_helpers_1.header)('Step 3 — Engineer (MCP Triage)');
    const engEsc = await (0, process_helpers_1.poll)('engineer escalation', async () => {
        const { escalations } = await (0, process_helpers_1.api)('GET', '/escalations/available?role=engineer&limit=50', engineerToken);
        return escalations.find((e) => e.id === escalation.id) ?? null;
    });
    await (0, process_helpers_1.api)('POST', `/escalations/${engEsc.id}/claim`, engineerToken);
    (0, process_helpers_1.log)('engineer', 'Claimed escalation');
    (0, process_helpers_1.log)('engineer', 'Content is in the wrong language. Requesting AI triage.');
    const resolveResult = await (0, process_helpers_1.api)('POST', `/escalations/${engEsc.id}/resolve`, engineerToken, {
        resolverPayload: {
            approved: false,
            reason: 'Content is in Spanish — needs translation before review',
            _lt: {
                needsTriage: true,
            },
            notes: 'Content arrived in Spanish. Needs translation to English before it can be reviewed.',
        },
    });
    (0, process_helpers_1.log)('engineer', `Triage started: ${resolveResult.triage ? 'yes' : 'no'} (workflow: ${resolveResult.workflowId?.slice(0, 20)}...)`);
    // ── 6. Wait for triage to complete ──────────────────────────────────────
    (0, process_helpers_1.header)('MCP Triage — Remediation');
    (0, process_helpers_1.log)('system', 'Waiting for triage workflow to translate and re-run ...');
    // Poll the process to see new tasks appear (triage + re-run)
    const processResult = await (0, process_helpers_1.poll)('triage completion', async () => {
        const detail = await (0, process_helpers_1.api)('GET', `/tasks/processes/${encodeURIComponent(originId)}`, engineerToken);
        const tasks = detail.tasks || [];
        // Look for a completed reviewContent re-run (from triage)
        const triageTask = tasks.find((t) => t.workflow_type === 'mcpTriage' && t.status === 'completed');
        const rerunTask = tasks.find((t) => t.workflow_type === 'reviewContent' &&
            t.status === 'completed' &&
            t.created_at > escalation.created_at);
        if (triageTask || rerunTask)
            return detail;
        return null;
    }, 45_000, 2_000);
    const tasks = processResult.tasks || [];
    const triageTask = tasks.find((t) => t.workflow_type?.includes('mcpTriage'));
    const rerunTask = tasks.find((t) => t.workflow_type === 'reviewContent' &&
        t.status === 'completed' &&
        t.created_at > escalation.created_at);
    if (triageTask) {
        (0, process_helpers_1.log)('mcp', `Triage workflow: ${triageTask.status}`);
    }
    if (rerunTask) {
        (0, process_helpers_1.log)('mcp', `Re-run workflow: ${rerunTask.status} (translated content auto-approved)`);
    }
    // ── 7. Check for engineering escalation ─────────────────────────────────
    (0, process_helpers_1.header)('Verification');
    // Check engineering escalation created by triage
    const engEscalation = await (0, process_helpers_1.poll)('engineering recommendation', async () => {
        const { escalations } = await (0, process_helpers_1.api)('GET', '/escalations/available?role=engineer&limit=50', engineerToken);
        return escalations.find((e) => e.type === 'triage_recommendation' &&
            e.origin_id === originId) ?? null;
    }, 30_000, 2_000);
    if (engEscalation) {
        (0, process_helpers_1.log)('verify', 'Engineering escalation created by triage');
        (0, process_helpers_1.log)('verify', `Description: ${engEscalation.description?.slice(0, 80)}...`);
        // Claim and acknowledge the notification escalation
        await (0, process_helpers_1.api)('POST', `/escalations/${engEscalation.id}/claim`, engineerToken);
        await (0, process_helpers_1.api)('POST', `/escalations/${engEscalation.id}/resolve`, engineerToken, {
            resolverPayload: { acknowledged: true, note: 'Will add language detection to pipeline' },
        });
        (0, process_helpers_1.log)('engineer', 'Acknowledged recommendation — will add language detection to pipeline');
    }
    // Summary
    const allTasks = tasks;
    const escalations = processResult.escalations || [];
    (0, process_helpers_1.log)('verify', `Process tasks: ${allTasks.length}`);
    (0, process_helpers_1.log)('verify', `Process escalations: ${escalations.length}`);
    (0, process_helpers_1.header)('Process Complete');
    console.log('  The full Durable MCP cycle:');
    console.log('');
    console.log('    Content arrived in Spanish');
    console.log('    → AI flagged (confidence: 0.15, wrong_language)');
    console.log('    → Escalated to reviewer');
    console.log('    → Reviewer escalated to admin (language issue)');
    console.log('    → Admin escalated to engineer (needs technical fix)');
    console.log('    → Engineer requested AI triage (LLM will diagnose and fix)');
    console.log('    → MCP orchestrator: translate_content() → re-invoke workflow');
    console.log('    → Translated content auto-approved');
    console.log('    → Engineering notified: add language detection to pipeline');
    console.log('    → Engineer acknowledged recommendation');
    console.log('');
    console.log('  ═════════════════════════════════════════════════════════════\n');
}
run().catch((err) => {
    console.error(`\n  ✗ ${err.message}\n`);
    process.exit(1);
});
