import { canonicalizePath } from "./session-selector-utils.js";
/**
 * Build a tree structure from sessions based on parentSessionPath.
 * Returns root nodes sorted by modified date (descending).
 */
export function buildSessionTree(sessions) {
    const byPath = new Map();
    for (const session of sessions) {
        const sessionPath = canonicalizePath(session.path) ?? session.path;
        byPath.set(sessionPath, { session, children: [] });
    }
    const roots = [];
    for (const session of sessions) {
        const sessionPath = canonicalizePath(session.path) ?? session.path;
        const node = byPath.get(sessionPath);
        const parentPath = canonicalizePath(session.parentSessionPath);
        if (parentPath && byPath.has(parentPath)) {
            byPath.get(parentPath).children.push(node);
        }
        else {
            roots.push(node);
        }
    }
    // Sort children and roots by modified date (descending)
    const sortNodes = (nodes) => {
        nodes.sort((a, b) => b.session.modified.getTime() - a.session.modified.getTime());
        for (const node of nodes) {
            sortNodes(node.children);
        }
    };
    sortNodes(roots);
    return roots;
}
/**
 * Flatten tree into display list with tree structure metadata.
 */
export function flattenSessionTree(roots) {
    const result = [];
    const walk = (node, depth, ancestorContinues, isLast) => {
        result.push({ session: node.session, depth, isLast, ancestorContinues });
        for (let i = 0; i < node.children.length; i++) {
            const childIsLast = i === node.children.length - 1;
            // Only show continuation line for non-root ancestors
            const continues = depth > 0 ? !isLast : false;
            walk(node.children[i], depth + 1, [...ancestorContinues, continues], childIsLast);
        }
    };
    for (let i = 0; i < roots.length; i++) {
        walk(roots[i], 0, [], i === roots.length - 1);
    }
    return result;
}
//# sourceMappingURL=session-selector-tree.js.map