const { fail } = require('./workspace.cjs'); const SAFE_ID_RE = /^[a-zA-Z0-9_-]{1,80}$/; function createEngineProxy({ baseUrl, serviceKey, fetchImpl = fetch, timeoutMs = 35000 } = {}) { const configuredUrl = String(baseUrl || '').trim().replace(/\/+$/, ''); const configuredKey = String(serviceKey || '').trim(); function isConfigured() { return Boolean(configuredUrl && configuredKey); } function assertConfigured() { if (!isConfigured()) { throw fail(503, 'ENGINE_NOT_CONFIGURED', 'Multi-Expert AI Engine সংযুক্ত নয়। অনুগ্রহ করে অ্যাডমিনের সাথে যোগাযোগ করুন।'); } } function cleanBody(body) { if (!body || typeof body !== 'object' || Array.isArray(body)) return {}; const out = { ...body }; delete out.tenant; delete out.tenant_id; delete out.clientId; delete out.client_id; return out; } async function forward(workspace, method, enginePath, body = null) { assertConfigured(); if (!workspace || !workspace.tenant || !workspace.clientId) { throw fail(401, 'WORKSPACE_REQUIRED', 'বৈধ workspace প্রয়োজন।'); } const url = configuredUrl + enginePath; const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), timeoutMs); const headers = { Authorization: 'Bearer ' + configuredKey, 'x-aura-tenant': workspace.tenant, 'x-aura-client-id': workspace.clientId, Accept: 'application/json' }; const init = { method, headers, signal: controller.signal }; if (body !== null && method !== 'GET' && method !== 'HEAD') { headers['Content-Type'] = 'application/json'; init.body = JSON.stringify(cleanBody(body)); } try { const upstream = await fetchImpl(url, init); const rawText = await upstream.text(); let parsed; try { parsed = rawText ? JSON.parse(rawText) : {}; } catch { parsed = { success: false, error: 'Engine returned invalid JSON' }; } if (!upstream.ok) { throw fail( upstream.status >= 400 && upstream.status < 600 ? upstream.status : 502, parsed.code || 'ENGINE_UPSTREAM_ERROR', parsed.error || 'AI Engine অনুরোধটি সম্পন্ন করতে পারেনি।' ); } return parsed; } catch (err) { if (err && Number.isInteger(err.status)) throw err; if (err && err.name === 'AbortError') { throw fail(504, 'ENGINE_TIMEOUT', 'AI Engine উত্তর দিতে বেশি সময় নিচ্ছে। একটু পরে আবার চেষ্টা করুন।'); } throw fail(502, 'ENGINE_UNREACHABLE', 'Multi-Expert AI Engine-এর সাথে সংযোগ পাওয়া যায়নি।'); } finally { clearTimeout(timer); } } return { isConfigured, listExperts: workspace => forward(workspace, 'GET', '/api/experts'), saveExpert: (workspace, body) => forward(workspace, 'POST', '/api/experts', body), deleteExpert: (workspace, id) => { if (!SAFE_ID_RE.test(String(id || ''))) { throw fail(400, 'INVALID_EXPERT_ID', 'সঠিক Expert ID দিন।'); } return forward(workspace, 'DELETE', '/api/experts/' + encodeURIComponent(id)); }, simulate: (workspace, body) => forward(workspace, 'POST', '/api/experts/simulate', body), generateContent: (workspace, body) => forward(workspace, 'POST', '/api/experts/generate-content', body), listPlaybooks: workspace => forward(workspace, 'GET', '/api/playbooks'), savePlaybook: (workspace, body) => forward(workspace, 'POST', '/api/playbooks', body), testPlaybook: (workspace, body) => forward(workspace, 'POST', '/api/playbooks/test', body) }; } module.exports = { createEngineProxy, SAFE_ID_RE };