import fs from 'node:fs/promises';
import fsSync from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { extractSessionIdentifiersFromMetadata } from './pipeline/session-identifiers.js';
import { normalizeToolSessionMessagesWithNative, updateToolSessionHistoryWithNative } from '../../router/virtual-router/engine-selection/native-hub-pipeline-req-outbound-semantics.js';
const TOOL_HISTORY_ROOT = path.join(os.homedir(), '.routecodex', 'tool-history');
function sanitizeSessionId(raw) {
    const trimmed = raw.trim();
    if (!trimmed) {
        return '';
    }
    return trimmed.replace(/[^A-Za-z0-9_.-]/g, '_');
}
async function loadSessionHistory(sessionId) {
    try {
        const file = path.join(TOOL_HISTORY_ROOT, `${sanitizeSessionId(sessionId)}.json`);
        if (!fsSync.existsSync(file)) {
            return null;
        }
        const text = await fs.readFile(file, 'utf-8');
        const parsed = JSON.parse(text);
        if (!parsed || typeof parsed !== 'object') {
            return null;
        }
        parsed.lastMessages = Array.isArray(parsed.lastMessages) ? parsed.lastMessages : [];
        parsed.pendingToolUses = parsed.pendingToolUses && typeof parsed.pendingToolUses === 'object'
            ? parsed.pendingToolUses
            : {};
        parsed.updatedAt = typeof parsed.updatedAt === 'string' && parsed.updatedAt.trim().length
            ? parsed.updatedAt
            : new Date().toISOString();
        return parsed;
    }
    catch {
        return null;
    }
}
async function persistSessionHistory(sessionId, history) {
    try {
        if (!fsSync.existsSync(TOOL_HISTORY_ROOT)) {
            await fs.mkdir(TOOL_HISTORY_ROOT, { recursive: true });
        }
        const file = path.join(TOOL_HISTORY_ROOT, `${sanitizeSessionId(sessionId)}.json`);
        const payload = JSON.stringify(history);
        await fs.writeFile(file, payload, 'utf-8');
    }
    catch {
        // history persistence must never block the main flow
    }
}
export async function applyToolSessionCompat(chat, ctx) {
    if (!chat || !Array.isArray(chat.messages) || chat.messages.length === 0) {
        return;
    }
    const normalized = normalizeToolSessionMessagesWithNative({
        messages: chat.messages,
        ...(Array.isArray(chat.toolOutputs) && chat.toolOutputs.length
            ? { toolOutputs: chat.toolOutputs }
            : {})
    });
    chat.messages = normalized.messages;
    chat.toolOutputs = Array.isArray(normalized.toolOutputs) && normalized.toolOutputs.length
        ? normalized.toolOutputs
        : undefined;
    const entry = (ctx.entryEndpoint || '').toLowerCase();
    if (!entry.includes('/v1/messages')) {
        return;
    }
    const metadata = (chat.metadata || {});
    const identifiers = extractSessionIdentifiersFromMetadata(metadata);
    const sessionId = identifiers.sessionId;
    if (!sessionId) {
        return;
    }
    const history = await loadSessionHistory(sessionId);
    const updated = updateToolSessionHistoryWithNative({
        messages: chat.messages,
        ...(history ? { existingHistory: history } : {})
    });
    if (!updated.history) {
        return;
    }
    await persistSessionHistory(sessionId, updated.history);
}
