"use strict";
/**
 * Shared Routes — Markdown file reading and description extraction
 *
 * Handles YAML frontmatter parsing, body-line extraction, and safe
 * bounded reads for both description snippets and full content.
 *
 * Directory walking is in shared-routes-markdown-walker.ts.
 */
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 (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveReadableMarkdownPath = exports.readMarkdownContent = exports.readFirstMarkdownDescription = exports.readMarkdownDescription = exports.extractDescription = exports.collectMarkdownFiles = exports.MAX_CONTENT_FILE_BYTES = void 0;
const fs = __importStar(require("fs"));
const yaml = __importStar(require("js-yaml"));
const shared_routes_path_guards_1 = require("./shared-routes-path-guards");
const MAX_DESCRIPTION_LENGTH = 140;
const MAX_MARKDOWN_FILE_BYTES = 1024 * 1024; // 1 MiB
/** Exported for content module which uses a larger limit. */
exports.MAX_CONTENT_FILE_BYTES = 2 * 1024 * 1024; // 2 MiB
var shared_routes_markdown_walker_1 = require("./shared-routes-markdown-walker");
Object.defineProperty(exports, "collectMarkdownFiles", { enumerable: true, get: function () { return shared_routes_markdown_walker_1.collectMarkdownFiles; } });
// ---------------------------------------------------------------------------
// Description extraction helpers
// ---------------------------------------------------------------------------
function isDescriptionBodyLine(line) {
    if (!line) {
        return false;
    }
    if (line === '---' || line === '...') {
        return false;
    }
    return !line.startsWith('#') && !line.startsWith('<!--');
}
function extractFrontmatterDescription(content) {
    const frontmatterMatch = content.match(/^---\s*\r?\n([\s\S]*?)\r?\n---(?:\s*\r?\n|$)/);
    if (!frontmatterMatch) {
        return null;
    }
    try {
        const parsed = yaml.load(frontmatterMatch[1]);
        const description = parsed?.description;
        if (typeof description !== 'string') {
            return null;
        }
        const trimmed = description.trim();
        return trimmed.length > 0 ? trimmed : null;
    }
    catch {
        return null;
    }
}
function stripFrontmatter(content) {
    return content.replace(/^---\s*\r?\n[\s\S]*?\r?\n---\s*\r?\n?/, '');
}
function trimDescription(description) {
    if (description.length <= MAX_DESCRIPTION_LENGTH) {
        return description;
    }
    return `${description.slice(0, MAX_DESCRIPTION_LENGTH - 3).trimEnd()}...`;
}
function extractDescription(content) {
    const frontmatterDescription = extractFrontmatterDescription(content);
    if (frontmatterDescription) {
        return trimDescription(frontmatterDescription);
    }
    // Fall back to first non-empty, non-heading body line.
    const lines = stripFrontmatter(content).split('\n');
    for (const line of lines) {
        const trimmed = line.trim();
        if (isDescriptionBodyLine(trimmed)) {
            return trimDescription(trimmed);
        }
    }
    return 'No description';
}
exports.extractDescription = extractDescription;
// ---------------------------------------------------------------------------
// File readers
// ---------------------------------------------------------------------------
function readMarkdownDescription(markdownPath, allowedRoots) {
    try {
        const resolvedMarkdownPath = (0, shared_routes_path_guards_1.safeRealPath)(markdownPath);
        if (!resolvedMarkdownPath || !(0, shared_routes_path_guards_1.isPathWithinAny)(resolvedMarkdownPath, allowedRoots)) {
            return null;
        }
        const stats = fs.statSync(resolvedMarkdownPath);
        if (!stats.isFile() || stats.size > MAX_MARKDOWN_FILE_BYTES) {
            return null;
        }
        const content = fs.readFileSync(resolvedMarkdownPath, 'utf8');
        return extractDescription(content);
    }
    catch {
        return null;
    }
}
exports.readMarkdownDescription = readMarkdownDescription;
function readFirstMarkdownDescription(markdownPaths, allowedRoots) {
    for (const markdownPath of markdownPaths) {
        const description = readMarkdownDescription(markdownPath, allowedRoots);
        if (description) {
            return description;
        }
    }
    return null;
}
exports.readFirstMarkdownDescription = readFirstMarkdownDescription;
function readMarkdownContent(markdownPath, allowedRoots) {
    try {
        const resolvedMarkdownPath = (0, shared_routes_path_guards_1.safeRealPath)(markdownPath);
        if (!resolvedMarkdownPath || !(0, shared_routes_path_guards_1.isPathWithinAny)(resolvedMarkdownPath, allowedRoots)) {
            return null;
        }
        const stats = fs.statSync(resolvedMarkdownPath);
        if (!stats.isFile() || stats.size > exports.MAX_CONTENT_FILE_BYTES) {
            return null;
        }
        return fs.readFileSync(resolvedMarkdownPath, 'utf8');
    }
    catch {
        return null;
    }
}
exports.readMarkdownContent = readMarkdownContent;
function resolveReadableMarkdownPath(markdownPaths, allowedRoots) {
    for (const markdownPath of markdownPaths) {
        const resolvedMarkdownPath = (0, shared_routes_path_guards_1.safeRealPath)(markdownPath);
        if (!resolvedMarkdownPath || !(0, shared_routes_path_guards_1.isPathWithinAny)(resolvedMarkdownPath, allowedRoots)) {
            continue;
        }
        try {
            const stats = fs.statSync(resolvedMarkdownPath);
            if (!stats.isFile() || stats.size > exports.MAX_CONTENT_FILE_BYTES) {
                continue;
            }
            return resolvedMarkdownPath;
        }
        catch {
            continue;
        }
    }
    return null;
}
exports.resolveReadableMarkdownPath = resolveReadableMarkdownPath;
//# sourceMappingURL=shared-routes-markdown.js.map