import { parseCellAnchor } from '../core/cell-anchor.js';
function toEnvelope(c) {
    // For dataset cell comments the anchor is JSON in anchor_relpos — surface
    // the column + row snapshot so an agent reading the comment as an entity can
    // locate the cell, not just see the bare cell value.
    const cell = parseCellAnchor(c.anchorRelpos);
    return {
        id: c.commentId,
        entityType: 'comment',
        data: {
            entity_type: 'comment',
            entity_id: c.commentId,
            created_at: c.createdAt,
            updated_at: c.updatedAt ?? c.createdAt,
            created_by: c.authorDisplayName,
            updated_by: c.authorDisplayName,
            // Comment-specific fields. Naming matches the SQL schema for
            // consistency with the public REST API.
            repo: c.repo,
            entry_type: c.entryType,
            entry_id: c.entryId,
            thread_id: c.threadId,
            parent_id: c.parentId,
            author_user_id: c.authorUserId,
            author_role: c.authorRole,
            anchor_quote: c.anchorQuote,
            ...(cell
                ? {
                    anchor_cell: {
                        column: cell.headerName,
                        column_index: cell.columnIndex,
                        ...(cell.rowCells ? { row_cells: cell.rowCells } : {}),
                    },
                }
                : {}),
            resolved_at: c.resolvedAt,
            resolved_by_user_id: c.resolvedByUserId,
            edited: c.edited === 1,
            mentions: c.mentions.map(m => m.handle),
        },
        document: { content: c.body, wikilinks: extractWikilinks(c.body) },
    };
}
const WIKILINK_RE = /\[\[([^\]|#]+)(?:\|[^\]]+)?\]\]/g;
function extractWikilinks(body) {
    const out = [];
    for (const match of body.matchAll(WIKILINK_RE)) {
        if (match[1])
            out.push(match[1].trim());
    }
    return out;
}
export function getComment(commentService, commentId) {
    const c = commentService.getById(commentId);
    if (!c || c.deletedAt)
        return null;
    return toEnvelope(c);
}
export function listComments(commentService, opts = {}) {
    return commentService.list(opts).map(toEnvelope);
}
/**
 * Comments anchored to a given entry — exposed as backlinks of that entry
 * so `find_related` includes them naturally.
 */
export function findRelatedComments(commentService, repo, entityType, entityId) {
    return commentService
        .list({ repo, entryType: entityType, entryId: entityId })
        .map(toEnvelope);
}
//# sourceMappingURL=comment-virtual-entity.js.map