let diagnosticSequence = 0;
let diagnosticSessionId;
export function isFieldValueDebugEnabled() {
    try {
        const meta = import.meta;
        if (meta.env?.DEV || meta.env?.MODE === "development")
            return true;
    }
    catch { }
    if (typeof window === "undefined")
        return false;
    try {
        const params = new URLSearchParams(window.location.search);
        if (isTruthyDebugValue(params.get("parhelia_field_debug")))
            return true;
        if (isTruthyDebugValue(params.get("parhelia_bridge_debug")))
            return true;
        if (params.get("parhelia_bridge_debug") === "verbose")
            return true;
        if (params.get("parhelia_field_debug") === "verbose")
            return true;
        const hostname = window.location.hostname;
        if (hostname === "localhost" ||
            hostname === "127.0.0.1" ||
            hostname === "::1") {
            return true;
        }
        return (isTruthyDebugValue(window.localStorage.getItem("parhelia:field-debug")) ||
            isTruthyDebugValue(window.localStorage.getItem("parhelia:bridge:debug")));
    }
    catch {
        return false;
    }
}
export function logFieldValueDiagnostic(stage, message, details) {
    if (!isFieldValueDebugEnabled())
        return;
    diagnosticSequence += 1;
    const payload = sanitizeDiagnosticDetails({
        diagnosticRun: getDiagnosticSessionId(),
        sequence: diagnosticSequence,
        at: new Date().toISOString(),
        performanceNow: typeof performance !== "undefined"
            ? Math.round(performance.now() * 100) / 100
            : undefined,
        ...details,
    });
    console.debug(`[Parhelia field] ${stage}: ${message}`, payload);
}
export function summarizeFieldDescriptor(descriptor) {
    if (!descriptor)
        return undefined;
    return {
        fieldId: descriptor.fieldId,
        itemId: descriptor.item?.id,
        language: descriptor.item?.language,
        version: descriptor.item?.version,
        itemName: descriptor.item?.displayName || descriptor.item?.name,
        path: descriptor.item?.path,
        database: descriptor.item?.database,
    };
}
export function summarizeField(field) {
    if (!field)
        return undefined;
    return {
        id: field.id,
        name: field.name,
        type: field.type,
        descriptor: summarizeFieldDescriptor(field.descriptor),
        value: summarizeFieldValue(field.value),
        rawValue: summarizeFieldValue(field.rawValue),
    };
}
export function summarizeFieldValue(value, previewLength = 120) {
    const text = value === undefined || value === null ? "" : String(value);
    const normalized = text.replace(/\u200B/g, "");
    const singleLinePreview = normalized
        .replace(/\s+/g, " ")
        .slice(0, previewLength);
    return {
        kind: value === null ? "null" : typeof value,
        length: text.length,
        normalizedLength: normalized.length,
        trimmedLength: normalized.trim().length,
        isEmpty: normalized.length === 0,
        isBlank: normalized.trim().length === 0,
        zeroWidthCount: text.length - normalized.length,
        hash: hashString(normalized),
        preview: normalized.length > previewLength
            ? `${singleLinePreview}...`
            : singleLinePreview,
    };
}
function getDiagnosticSessionId() {
    if (diagnosticSessionId)
        return diagnosticSessionId;
    const random = typeof crypto !== "undefined" && "randomUUID" in crypto
        ? crypto.randomUUID()
        : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
    diagnosticSessionId = random.slice(0, 12);
    return diagnosticSessionId;
}
function isTruthyDebugValue(value) {
    return value === "1" || value === "true" || value === "verbose";
}
function sanitizeDiagnosticDetails(value) {
    if (Array.isArray(value)) {
        return value.map(sanitizeDiagnosticDetails);
    }
    if (!value || typeof value !== "object") {
        return value;
    }
    const result = {};
    for (const [key, nestedValue] of Object.entries(value)) {
        if (/token|secret|signedContext|sessionId/i.test(key)) {
            result[key] = "[redacted]";
        }
        else {
            result[key] = sanitizeDiagnosticDetails(nestedValue);
        }
    }
    return result;
}
function hashString(value) {
    let hash = 2166136261;
    for (let i = 0; i < value.length; i += 1) {
        hash ^= value.charCodeAt(i);
        hash = Math.imul(hash, 16777619);
    }
    return (hash >>> 0).toString(16).padStart(8, "0");
}
//# sourceMappingURL=fieldValueDiagnostics.js.map