"use strict";
// v1.12.0 — StoryRegistry.
//
// Filesystem scanner + in-memory index of stories and epics. Looks
// at `<cwd>/docs/stories/<epic-id>/*.story.md` and `epic.md` by
// default. Override roots via OPENLIFE_STORY_DIR (single path) or
// pass explicit `roots[]` to `load()`.
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 });
exports.StoryRegistry = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const StoryParser_1 = require("./StoryParser");
const STORY_FILE_RE = /\.story\.md$/i;
const EPIC_FILE_RE = /^epic\.md$/i;
class StoryRegistry {
    storiesById = new Map();
    epicsById = new Map();
    lastErrors = [];
    rootsScanned = [];
    /**
     * Build the list of roots to scan, in priority order. First wins per
     * story id (so a per-project story overrides one from ~/.openlife/stories).
     */
    static defaultRoots(cwd = process.cwd()) {
        const roots = [];
        const projectRoot = path.join(cwd, 'docs', 'stories');
        roots.push(projectRoot);
        const envRoot = (process.env.OPENLIFE_STORY_DIR || '').trim();
        if (envRoot)
            roots.push(envRoot);
        const home = process.env.HOME || process.env.USERPROFILE;
        if (home)
            roots.push(path.join(home, '.openlife', 'stories'));
        return roots;
    }
    async load(roots) {
        this.storiesById.clear();
        this.epicsById.clear();
        this.lastErrors = [];
        this.rootsScanned = [];
        const resolvedRoots = roots && roots.length > 0 ? roots : StoryRegistry.defaultRoots();
        for (const root of resolvedRoots) {
            if (!fs.existsSync(root))
                continue;
            try {
                const stat = fs.statSync(root);
                if (!stat.isDirectory())
                    continue;
            }
            catch {
                continue;
            }
            this.rootsScanned.push(root);
            const epicDirs = this.listEpicDirs(root);
            for (const epicDir of epicDirs)
                this.loadEpicDir(epicDir);
        }
        return {
            stories: Array.from(this.storiesById.values()),
            epics: Array.from(this.epicsById.values()),
            errors: this.lastErrors,
            rootsScanned: this.rootsScanned.slice(),
        };
    }
    refresh() {
        return this.load();
    }
    get(id) {
        return this.storiesById.get(id) || null;
    }
    getEpic(id) {
        return this.epicsById.get(id) || null;
    }
    list(filter) {
        const all = Array.from(this.storiesById.values());
        if (!filter)
            return all;
        return all.filter(s => (!filter.epicId || s.epicId === filter.epicId) &&
            (!filter.status || s.status === filter.status) &&
            (!filter.cluster || s.cluster === filter.cluster) &&
            (!filter.severity || s.severity === filter.severity));
    }
    listEpics() {
        return Array.from(this.epicsById.values());
    }
    findByEpic(epicId) {
        return this.list({ epicId });
    }
    findByStatus(status) {
        return this.list({ status });
    }
    findByDependency(storyId) {
        return Array.from(this.storiesById.values()).filter(s => s.dependsOn.includes(storyId));
    }
    errors() {
        return this.lastErrors.slice();
    }
    listEpicDirs(root) {
        let entries;
        try {
            entries = fs.readdirSync(root);
        }
        catch {
            return [];
        }
        const out = [];
        for (const name of entries) {
            const full = path.join(root, name);
            try {
                if (fs.statSync(full).isDirectory())
                    out.push(full);
            }
            catch { /* ignore */ }
        }
        return out;
    }
    loadEpicDir(epicDir) {
        let entries;
        try {
            entries = fs.readdirSync(epicDir);
        }
        catch {
            return;
        }
        for (const name of entries) {
            const full = path.join(epicDir, name);
            if (EPIC_FILE_RE.test(name))
                this.ingestEpicFile(full);
            else if (STORY_FILE_RE.test(name))
                this.ingestStoryFile(full);
        }
    }
    ingestStoryFile(filePath) {
        let content;
        try {
            content = fs.readFileSync(filePath, 'utf-8');
        }
        catch (err) {
            this.lastErrors.push({ sourcePath: filePath, message: `read failed: ${err instanceof Error ? err.message : String(err)}` });
            return;
        }
        const parsed = (0, StoryParser_1.parseStory)(content, filePath);
        if (parsed.errors.length > 0)
            this.lastErrors.push(...parsed.errors);
        if (parsed.value && parsed.value.id && !this.storiesById.has(parsed.value.id)) {
            this.storiesById.set(parsed.value.id, parsed.value);
        }
    }
    ingestEpicFile(filePath) {
        let content;
        try {
            content = fs.readFileSync(filePath, 'utf-8');
        }
        catch (err) {
            this.lastErrors.push({ sourcePath: filePath, message: `read failed: ${err instanceof Error ? err.message : String(err)}` });
            return;
        }
        const parsed = (0, StoryParser_1.parseEpic)(content, filePath);
        if (parsed.errors.length > 0)
            this.lastErrors.push(...parsed.errors);
        if (parsed.value && parsed.value.id && !this.epicsById.has(parsed.value.id)) {
            this.epicsById.set(parsed.value.id, parsed.value);
        }
    }
}
exports.StoryRegistry = StoryRegistry;
