"use strict";
// test_logs_command — verifies filter / tail / since semantics + duration
// parser of `openlife logs`.
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 LogsCommand_1 = require("./cli/LogsCommand");
function assert(cond, msg) {
    if (!cond) {
        console.error(`❌ ASSERT FAILED: ${msg}`);
        process.exit(1);
    }
}
function tempRoot() {
    const root = fs.mkdtempSync(path.join(os.tmpdir(), 'openlife-logs-'));
    fs.mkdirSync(path.join(root, '.openlife'), { recursive: true });
    return root;
}
function cleanup(root) {
    try {
        fs.rmSync(root, { recursive: true, force: true });
    }
    catch {
        // best-effort
    }
}
function writeJsonl(root, filename, entries) {
    fs.writeFileSync(path.join(root, '.openlife', filename), entries.map((e) => JSON.stringify(e)).join('\n') + '\n', 'utf-8');
}
function scenarioDurationParser() {
    assert((0, LogsCommand_1.parseDurationToSeconds)('30s') === 30, '30s → 30');
    assert((0, LogsCommand_1.parseDurationToSeconds)('5m') === 300, '5m → 300');
    assert((0, LogsCommand_1.parseDurationToSeconds)('1h') === 3600, '1h → 3600');
    assert((0, LogsCommand_1.parseDurationToSeconds)('2d') === 172800, '2d → 172800');
    assert((0, LogsCommand_1.parseDurationToSeconds)('bogus') === null, 'bogus → null');
    assert((0, LogsCommand_1.parseDurationToSeconds)('-1m') === null, 'negative → null');
    console.log('✅ scenario 1: parseDurationToSeconds covers s/m/h/d + rejects garbage');
}
function scenarioTailDefault() {
    const root = tempRoot();
    try {
        const entries = [];
        const now = Date.now();
        for (let i = 0; i < 50; i++) {
            entries.push({ ts: new Date(now - (50 - i) * 1000).toISOString(), summary: `entry ${i}` });
        }
        writeJsonl(root, 'governance-ledger.jsonl', entries);
        const collected = (0, LogsCommand_1.collectLogs)({ root, tail: 5 });
        assert(collected.length === 5, `expected 5 entries, got ${collected.length}`);
        assert(collected[collected.length - 1].parsed.summary === 'entry 49', 'last entry should be the newest');
        console.log('✅ scenario 2: tail=5 returns last 5 chronological entries');
    }
    finally {
        cleanup(root);
    }
}
function scenarioFilterBySubsystem() {
    const root = tempRoot();
    try {
        const now = Date.now();
        const govEntries = [
            { ts: new Date(now).toISOString(), summary: 'gov-entry' },
        ];
        const mediaEntries = [
            { ts: new Date(now).toISOString(), summary: 'media-entry' },
        ];
        writeJsonl(root, 'governance-ledger.jsonl', govEntries);
        writeJsonl(root, 'media-routing.log.jsonl', mediaEntries);
        const govOnly = (0, LogsCommand_1.collectLogs)({ root, filter: 'governance' });
        assert(govOnly.length === 1, `expected 1 governance entry, got ${govOnly.length}`);
        assert(govOnly[0].subsystem === 'governance-ledger', 'subsystem should match');
        const mediaOnly = (0, LogsCommand_1.collectLogs)({ root, filter: 'media' });
        assert(mediaOnly.length === 1, `expected 1 media entry, got ${mediaOnly.length}`);
        assert(mediaOnly[0].subsystem === 'media-routing', 'media subsystem name');
        console.log('✅ scenario 3: --filter narrows by subsystem id');
    }
    finally {
        cleanup(root);
    }
}
function scenarioSinceFiltersOldEntries() {
    const root = tempRoot();
    try {
        const now = Date.now();
        const entries = [
            { ts: new Date(now - 3600_000).toISOString(), summary: 'one-hour-ago' },
            { ts: new Date(now - 60_000).toISOString(), summary: 'one-minute-ago' },
            { ts: new Date(now - 5_000).toISOString(), summary: 'five-seconds-ago' },
        ];
        writeJsonl(root, 'governance-ledger.jsonl', entries);
        const recent = (0, LogsCommand_1.collectLogs)({ root, since: '5m' });
        assert(recent.length === 2, `expected 2 entries within 5m, got ${recent.length}`);
        assert(!recent.some((e) => e.parsed.summary === 'one-hour-ago'), 'one-hour-ago should be excluded');
        console.log('✅ scenario 4: --since=5m excludes older entries');
    }
    finally {
        cleanup(root);
    }
}
function scenarioRenderHumanAndJson() {
    const root = tempRoot();
    try {
        writeJsonl(root, 'governance-ledger.jsonl', [
            { ts: new Date().toISOString(), summary: 'test summary' },
        ]);
        const entries = (0, LogsCommand_1.collectLogs)({ root });
        const human = (0, LogsCommand_1.renderLogsHuman)(entries);
        assert(human.includes('[governance-ledger]'), 'human render includes subsystem');
        assert(human.includes('test summary'), 'human render includes summary');
        const jsonLine = (0, LogsCommand_1.renderLogsJson)(entries);
        const parsed = JSON.parse(jsonLine);
        assert(parsed.subsystem === 'governance-ledger', 'json render preserves subsystem');
        console.log('✅ scenario 5: human + JSON renderers both produce expected shape');
    }
    finally {
        cleanup(root);
    }
}
function scenarioNoEntriesGracefullyHandled() {
    const root = tempRoot();
    try {
        const entries = (0, LogsCommand_1.collectLogs)({ root });
        assert(entries.length === 0, 'no jsonl files → empty result');
        const human = (0, LogsCommand_1.renderLogsHuman)(entries);
        assert(human.includes('no entries'), 'human render reports empty');
        console.log('✅ scenario 6: empty state renders helpful message');
    }
    finally {
        cleanup(root);
    }
}
function main() {
    console.log('🧪 test_logs_command — jsonl viewer');
    scenarioDurationParser();
    scenarioTailDefault();
    scenarioFilterBySubsystem();
    scenarioSinceFiltersOldEntries();
    scenarioRenderHumanAndJson();
    scenarioNoEntriesGracefullyHandled();
    console.log('');
    console.log('TEST_LOGS_COMMAND_OK');
}
main();
