"use strict";
/**
 * test_core_remote_command — v1.11.0 regression suite.
 *
 * Asserts:
 *   1. parse() correctly splits /core <verb> <args...>
 *   2. /core status returns presence directly (no inbox)
 *   3. /core run enqueues inbox message
 *   4. Unsupported verb is rejected with clear error
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
const fs = __importStar(require("fs"));
const os = __importStar(require("os"));
const path = __importStar(require("path"));
const CoreRemoteCommand_1 = require("./orchestrator/CoreRemoteCommand");
const CliInbox_1 = require("./cli/CliInbox");
const CorePresence_1 = require("./cli/CorePresence");
function assert(cond, msg) {
    if (!cond)
        throw new Error(`assertion failed: ${msg}`);
}
function mkTmp() {
    return fs.mkdtempSync(path.join(os.tmpdir(), 'core-rc-test-'));
}
function rmTmp(dir) {
    try {
        fs.rmSync(dir, { recursive: true, force: true });
    }
    catch { /* ignore */ }
}
async function withHome(home, fn) {
    const prev = process.env.HOME;
    process.env.HOME = home;
    try {
        return await fn();
    }
    finally {
        if (prev === undefined)
            delete process.env.HOME;
        else
            process.env.HOME = prev;
    }
}
function scenarioParse() {
    assert(CoreRemoteCommand_1.CoreRemoteCommand.parse('/core status')?.verb === 'status', '/core status');
    assert(CoreRemoteCommand_1.CoreRemoteCommand.parse('/core run my task here')?.args.length === 3, 'run args');
    assert(CoreRemoteCommand_1.CoreRemoteCommand.parse('/core')?.verb === 'status', 'bare /core defaults to status');
    assert(CoreRemoteCommand_1.CoreRemoteCommand.parse('not-a-core-cmd') === null, 'non-/core returns null');
    console.log('✅ scenario 1: parse extracts verb + args');
}
async function scenarioStatusDirect() {
    const tmp = mkTmp();
    try {
        await withHome(tmp, async () => {
            // No presence file yet
            let r = await CoreRemoteCommand_1.CoreRemoteCommand.handle('/core status');
            assert(r.routed === 'direct', 'status routes direct');
            assert(r.reply.includes('sem core-presence.json') || r.reply.includes('STALE') || r.reply.includes('FRESH'), 'mentions presence state');
            // Publish presence
            CorePresence_1.CorePresence.publish('bridge status');
            r = await CoreRemoteCommand_1.CoreRemoteCommand.handle('/core status');
            assert(r.reply.includes('FRESH'), 'after publish, presence is FRESH');
        });
        console.log('✅ scenario 2: /core status answered directly via CorePresence');
    }
    finally {
        rmTmp(tmp);
    }
}
async function scenarioRunEnqueues() {
    const tmp = mkTmp();
    try {
        await withHome(tmp, async () => {
            CorePresence_1.CorePresence.publish('test');
            const r = await CoreRemoteCommand_1.CoreRemoteCommand.handle('/core run build-project');
            assert(r.routed === 'inbox', 'run goes to inbox');
            assert(r.messageId.length > 0, 'inbox message id returned');
            const pending = await CliInbox_1.CliInbox.drain();
            assert(pending.length === 1, `inbox must have 1 message, got ${pending.length}`);
            assert(pending[0].verb === 'run', 'verb is run');
            assert(pending[0].args.includes('build-project'), 'args preserved');
            assert(pending[0].origin === 'telegram', 'origin set');
        });
        console.log('✅ scenario 3: /core run enqueues into cli-inbox');
    }
    finally {
        rmTmp(tmp);
    }
}
async function scenarioUnsupportedVerb() {
    const tmp = mkTmp();
    try {
        await withHome(tmp, async () => {
            const r = await CoreRemoteCommand_1.CoreRemoteCommand.handle('/core nuke');
            assert(r.routed === 'rejected', 'unknown verb rejected');
            assert(r.reply.toLowerCase().includes('não suportado') || r.reply.toLowerCase().includes('not supported'), 'reply explains');
        });
        console.log('✅ scenario 4: unsupported verb is rejected');
    }
    finally {
        rmTmp(tmp);
    }
}
(async () => {
    try {
        scenarioParse();
        await scenarioStatusDirect();
        await scenarioRunEnqueues();
        await scenarioUnsupportedVerb();
        console.log('TEST_CORE_REMOTE_COMMAND_OK');
    }
    catch (err) {
        console.error('TEST_CORE_REMOTE_COMMAND_FAIL', err);
        process.exit(1);
    }
})();
