/**
 * Bash stream processor — single-pass UTF-8 decode + ANSI strip + binary sanitization.
 *
 * Uses native Rust implementation when available, with JS fallbacks.
 */
import { native } from "../native.js";
// ── Native availability check ─────────────────────────────────────────────────
let _nativeAvailable = null;
function nativeAvailable() {
    if (_nativeAvailable === null) {
        try {
            native.stripAnsiNative("test");
            _nativeAvailable = true;
        }
        catch {
            _nativeAvailable = false;
        }
    }
    return _nativeAvailable;
}
// ── JS fallbacks ──────────────────────────────────────────────────────────────
const ANSI_RE = /\x1b\[[0-9;]*[a-zA-Z]|\x1b\][^\x07]*\x07|\x1b[()][AB012]|\x1b\[[\?=]?[0-9;]*[a-zA-Z]/g;
function jsStripAnsi(text) {
    return text.replace(ANSI_RE, "");
}
function jsSanitizeBinaryOutput(text) {
    // Keep tab (0x09) and newline (0x0a), remove CR and other controls
    return text
        .replace(/\r/g, "")
        .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, "")
        .replace(/[\ufff9-\ufffb]/g, "");
}
function jsProcessStreamChunk(chunk, _state) {
    // Simple JS fallback: decode UTF-8, strip ANSI, sanitize
    const text = jsSanitizeBinaryOutput(jsStripAnsi(chunk.toString("utf-8")));
    return {
        text,
        state: { utf8Pending: [], ansiPending: [] },
    };
}
// ── Exported functions ────────────────────────────────────────────────────────
export function processStreamChunk(chunk, state) {
    if (nativeAvailable()) {
        const napiState = state
            ? {
                utf8Pending: Array.from(state.utf8Pending),
                ansiPending: Array.from(state.ansiPending),
            }
            : undefined;
        const result = native.processStreamChunk(chunk, napiState);
        return {
            text: result.text,
            state: {
                utf8Pending: Array.from(result.state.utf8Pending),
                ansiPending: Array.from(result.state.ansiPending),
            },
        };
    }
    return jsProcessStreamChunk(chunk, state);
}
export function stripAnsiNative(text) {
    if (nativeAvailable()) {
        return native.stripAnsiNative(text);
    }
    return jsStripAnsi(text);
}
export function sanitizeBinaryOutputNative(text) {
    if (nativeAvailable()) {
        return native.sanitizeBinaryOutputNative(text);
    }
    return jsSanitizeBinaryOutput(text);
}
