"use strict";
// v1.12.0 — StoryLifecycle.
//
// Pure state-machine guards for story status transitions. No file
// I/O. Lifecycle rules are inline (no external rules file exists
// in this repo). Role check uses OPENLIFE_USER_ROLE (default "dev").
//
//      Draft → Ready              (po)
//      Ready → InProgress         (dev)
//      InProgress → InReview      (dev)
//      InReview → Done            (qa | po)
//      InReview → InProgress      (dev)        — reopen on review feedback
Object.defineProperty(exports, "__esModule", { value: true });
exports._internals = exports.KNOWN_ROLES = void 0;
exports.isRole = isRole;
exports.currentRole = currentRole;
exports.canTransition = canTransition;
exports.allowedNextStates = allowedNextStates;
const StorySchema_1 = require("./StorySchema");
exports.KNOWN_ROLES = ['po', 'dev', 'qa', 'admin'];
function isRole(v) {
    return exports.KNOWN_ROLES.includes(v);
}
const EDGES = [
    { from: 'Draft', to: 'Ready', roles: ['po', 'admin'] },
    { from: 'Ready', to: 'InProgress', roles: ['dev', 'admin'] },
    { from: 'InProgress', to: 'InReview', roles: ['dev', 'admin'] },
    { from: 'InReview', to: 'Done', roles: ['qa', 'po', 'admin'] },
    { from: 'InReview', to: 'InProgress', roles: ['dev', 'admin'] },
];
function currentRole(envRole) {
    const raw = (envRole ?? process.env.OPENLIFE_USER_ROLE ?? 'dev').toLowerCase().trim();
    return isRole(raw) ? raw : 'dev';
}
function canTransition(from, to, role = currentRole()) {
    if (!(0, StorySchema_1.isStoryStatus)(from))
        return { allowed: false, reason: `unknown current status "${from}". Expected one of: ${StorySchema_1.STORY_STATUSES.join(', ')}` };
    if (!(0, StorySchema_1.isStoryStatus)(to))
        return { allowed: false, reason: `unknown target status "${to}". Expected one of: ${StorySchema_1.STORY_STATUSES.join(', ')}` };
    if (from === to)
        return { allowed: false, reason: `already in status "${from}"` };
    const edge = EDGES.find(e => e.from === from && e.to === to);
    if (!edge) {
        const allowedTargets = EDGES.filter(e => e.from === from).map(e => e.to);
        const hint = allowedTargets.length > 0 ? `Allowed from "${from}": ${allowedTargets.join(', ')}` : `No transitions defined from "${from}"`;
        return { allowed: false, reason: `transition "${from}" → "${to}" is not defined. ${hint}` };
    }
    if (!edge.roles.includes(role)) {
        return { allowed: false, reason: `role "${role}" cannot apply transition "${from}" → "${to}". Allowed roles: ${edge.roles.join(', ')}`, edge };
    }
    return { allowed: true, edge };
}
/** Helper for CLI/HTTP surface: enumerate all transitions from a status. */
function allowedNextStates(from) {
    if (!(0, StorySchema_1.isStoryStatus)(from))
        return [];
    return EDGES.filter(e => e.from === from).map(e => e.to);
}
exports._internals = { EDGES };
