"use strict";
// src/orchestrator/rag/Chunker.ts
// v1.13.0 — Language-agnostic file chunker.
//
// Splits content into chunks suited for embedding. For TS/JS files we
// look for top-level `export (function|class|const|interface|type|enum)`
// markers as soft boundaries; for everything else we fall back to a
// sliding window. Chunks are capped at ~512 "tokens" (char/4 heuristic
// — tiktoken arrives with v1.14).
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.inferLanguage = inferLanguage;
exports.approxTokens = approxTokens;
exports.chunkFile = chunkFile;
const path = __importStar(require("path"));
const DEFAULT_WINDOW = 40;
const DEFAULT_OVERLAP = 8;
const TOKEN_CHAR_RATIO = 4;
const HARD_TOKEN_CAP = 512;
const TS_BOUNDARY_RE = /^export\s+(?:async\s+)?(?:function|class|const|interface|type|enum|abstract\s+class|default\s+(?:async\s+)?(?:function|class))\b/;
function inferLanguage(filePath) {
    const ext = path.extname(filePath).toLowerCase();
    switch (ext) {
        case '.ts':
        case '.tsx': return 'ts';
        case '.js':
        case '.mjs':
        case '.cjs':
        case '.jsx': return 'js';
        case '.py': return 'py';
        case '.go': return 'go';
        case '.rs': return 'rs';
        case '.java': return 'java';
        case '.rb': return 'rb';
        case '.md': return 'md';
        case '.json': return 'json';
        case '.yaml':
        case '.yml': return 'yaml';
        default: return undefined;
    }
}
function approxTokens(s) {
    return Math.ceil(s.length / TOKEN_CHAR_RATIO);
}
function chunkFile(filePath, content, opts = {}) {
    const lang = inferLanguage(filePath);
    const lines = content.split(/\r?\n/);
    if (lines.length === 0)
        return [];
    if (lang === 'ts' || lang === 'js') {
        const boundaryChunks = splitByTsBoundaries(lines, opts);
        if (boundaryChunks.length > 0)
            return tagLanguage(boundaryChunks, lang);
    }
    return tagLanguage(slidingWindow(lines, opts), lang);
}
function splitByTsBoundaries(lines, opts) {
    const boundaries = [];
    for (let i = 0; i < lines.length; i++) {
        if (TS_BOUNDARY_RE.test(lines[i]))
            boundaries.push(i);
    }
    if (boundaries.length === 0)
        return [];
    boundaries.push(lines.length);
    const tokenCap = opts.tokenCap ?? HARD_TOKEN_CAP;
    const chunks = [];
    for (let b = 0; b < boundaries.length - 1; b++) {
        const start = boundaries[b];
        const end = boundaries[b + 1] - 1;
        const segment = lines.slice(start, end + 1).join('\n');
        if (approxTokens(segment) <= tokenCap) {
            chunks.push({ startLine: start + 1, endLine: end + 1, content: segment });
        }
        else {
            // Boundary segment too large — re-chunk it with sliding window.
            const inner = slidingWindow(lines.slice(start, end + 1), opts).map(c => ({
                startLine: c.startLine + start,
                endLine: c.endLine + start,
                content: c.content,
            }));
            chunks.push(...inner);
        }
    }
    return chunks;
}
function slidingWindow(lines, opts) {
    const win = opts.windowLines ?? DEFAULT_WINDOW;
    const overlap = Math.min(opts.overlapLines ?? DEFAULT_OVERLAP, Math.max(0, win - 1));
    const step = Math.max(1, win - overlap);
    const tokenCap = opts.tokenCap ?? HARD_TOKEN_CAP;
    const out = [];
    for (let i = 0; i < lines.length; i += step) {
        const end = Math.min(lines.length, i + win);
        const segment = lines.slice(i, end).join('\n');
        if (segment.trim().length === 0)
            continue;
        if (approxTokens(segment) <= tokenCap) {
            out.push({ startLine: i + 1, endLine: end, content: segment });
        }
        else {
            // Reduce window by half until the chunk fits.
            let sub = win;
            while (sub > 4) {
                sub = Math.max(4, Math.floor(sub / 2));
                const subEnd = Math.min(lines.length, i + sub);
                const subSeg = lines.slice(i, subEnd).join('\n');
                if (approxTokens(subSeg) <= tokenCap) {
                    out.push({ startLine: i + 1, endLine: subEnd, content: subSeg });
                    break;
                }
            }
        }
        if (end >= lines.length)
            break;
    }
    return out;
}
function tagLanguage(chunks, language) {
    if (!language)
        return chunks;
    return chunks.map(c => ({ ...c, language }));
}
