"use strict";
/**
 * test_story_registry — v1.12.0 StoryRegistry regression suite.
 *
 * Builds a tmpdir snapshot of docs/stories/ shape and asserts:
 *   - load() returns stories + epics
 *   - get(id), findByEpic(), findByStatus(), findByDependency() round-trip
 *   - first-root-wins on duplicate story ids across roots
 *   - missing dirs are tolerated (no throw)
 *
 * Run via: `npm run test:story-registry`.
 */
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 StoryRegistry_1 = require("./orchestrator/story/StoryRegistry");
function assert(cond, msg) {
    if (!cond)
        throw new Error(`assertion failed: ${msg}`);
}
function mkTmp() {
    return fs.mkdtempSync(path.join(os.tmpdir(), 'storyreg-'));
}
function rmTmp(dir) {
    try {
        fs.rmSync(dir, { recursive: true, force: true });
    }
    catch { /* ignore */ }
}
function writeStory(root, epicId, storyId, status, dependsOn = []) {
    const dir = path.join(root, epicId);
    fs.mkdirSync(dir, { recursive: true });
    const fp = path.join(dir, `${storyId}.story.md`);
    const dep = dependsOn.length > 0 ? `**Depends on:** ${dependsOn.map(d => `Story ${d}`).join(', ')}\n` : '';
    fs.writeFileSync(fp, [
        `# Story ${storyId} — synthetic`,
        '',
        `**StoryId:** \`${storyId}\``,
        `**Epic:** \`${epicId}\``,
        `**Status:** ${status}`,
        `**Cluster:** test-cluster`,
        dep,
        '## Acceptance Criteria',
        '',
        '- [ ] something',
    ].join('\n'));
    return fp;
}
function writeEpic(root, epicId, status) {
    const dir = path.join(root, epicId);
    fs.mkdirSync(dir, { recursive: true });
    const fp = path.join(dir, 'epic.md');
    fs.writeFileSync(fp, [
        `# Epic: ${epicId}`,
        '',
        `**EpicId:** \`${epicId}\``,
        `**Status:** ${status}`,
        '',
        '## Goal',
        '',
        'Synthetic test epic.',
    ].join('\n'));
    return fp;
}
async function basicRoundTrip() {
    const tmp = mkTmp();
    try {
        writeEpic(tmp, 'epic-a', 'Ready');
        writeStory(tmp, 'epic-a', '1.1', 'Ready');
        writeStory(tmp, 'epic-a', '1.2', 'InProgress', ['1.1']);
        writeStory(tmp, 'epic-a', '1.3', 'InReview', ['1.1', '1.2']);
        const reg = new StoryRegistry_1.StoryRegistry();
        const result = await reg.load([tmp]);
        assert(result.stories.length === 3, `expected 3 stories, got ${result.stories.length}`);
        assert(result.epics.length === 1, `expected 1 epic, got ${result.epics.length}`);
        assert(reg.get('1.2')?.status === 'InProgress', 'get(1.2) status mismatch');
        assert(reg.findByEpic('epic-a').length === 3, 'findByEpic missed stories');
        assert(reg.findByStatus('Ready').length === 1, 'findByStatus(Ready) mismatch');
        assert(reg.findByDependency('1.1').length === 2, 'findByDependency(1.1) should return 1.2 and 1.3');
        assert(reg.getEpic('epic-a')?.status === 'Ready', 'epic status mismatch');
    }
    finally {
        rmTmp(tmp);
    }
}
async function firstRootWins() {
    const a = mkTmp();
    const b = mkTmp();
    try {
        writeStory(a, 'epic-x', '5.1', 'Ready'); // primary
        writeStory(b, 'epic-x', '5.1', 'Done'); // shadowed
        writeStory(b, 'epic-x', '5.2', 'Ready'); // unique to b — should appear
        const reg = new StoryRegistry_1.StoryRegistry();
        const result = await reg.load([a, b]);
        assert(result.stories.length === 2, `expected 2 unique stories, got ${result.stories.length}`);
        assert(reg.get('5.1')?.status === 'Ready', 'first root should win for 5.1');
        assert(reg.get('5.2')?.status === 'Ready', '5.2 from second root should be present');
    }
    finally {
        rmTmp(a);
        rmTmp(b);
    }
}
async function missingRootsTolerated() {
    const reg = new StoryRegistry_1.StoryRegistry();
    const result = await reg.load(['/nonexistent/path/should/not/throw']);
    assert(result.stories.length === 0, 'expected 0 stories from missing root');
    assert(result.epics.length === 0, 'expected 0 epics from missing root');
    assert(result.errors.length === 0, 'missing root should not produce errors');
}
async function refreshRescans() {
    const tmp = mkTmp();
    try {
        writeStory(tmp, 'epic-r', '7.1', 'Ready');
        const reg = new StoryRegistry_1.StoryRegistry();
        await reg.load([tmp]);
        assert(reg.list().length === 1, 'expected 1 story before refresh');
        // Add another story and refresh — but registry's defaultRoots looks at cwd.
        // We re-load with explicit roots instead.
        writeStory(tmp, 'epic-r', '7.2', 'Ready');
        await reg.load([tmp]);
        assert(reg.list().length === 2, 'expected 2 stories after re-load');
    }
    finally {
        rmTmp(tmp);
    }
}
async function main() {
    await basicRoundTrip();
    await firstRootWins();
    await missingRootsTolerated();
    await refreshRescans();
    console.log('TEST_STORY_REGISTRY_OK');
}
main().catch(e => {
    console.error('TEST_STORY_REGISTRY_FAIL:', e instanceof Error ? e.message : e);
    process.exit(1);
});
