// Modultests für aria-gateway.ts: Konfiguration, Anfrage (Absender nur aus ctx.from.id),
// Antwortprüfung, Entscheidungslogik, echter Bridge-Prozess (Mock-Bridge), Nebenläufigkeit.
import { beforeEach, describe, expect, test } from 'bun:test'
import { createHash } from 'node:crypto'
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import {
  buildRequest, channelParams, createAriaGateway, decideActive, failureVerdict, GatewayInputError, LIMITS,
  NON_FORWARD_HANDLINGS, oneShotRemainder, readSettings, runBridgeProcess, TEXTS, validateResponse,
  type BridgeOutcome, type BridgeRequest, type GatewaySettings,
} from '../plugin/aria-gateway.ts'
import { HARNESS_ROOT, WORK } from './harness.ts'

const MOCK = join(HARNESS_ROOT, 'test', 'fixtures', 'mock_bridge.py')
const SCHEMA = JSON.parse(readFileSync(join(HARNESS_ROOT, 'docs', 'bridge-protokoll.schema.json'), 'utf8'))
const OWNER_ID = 100200300
const STRANGER_ID = 999888777

let dirCounter = 0
function scenarioDir(): string {
  const dir = join(WORK, 'unit', String(++dirCounter))
  rmSync(dir, { recursive: true, force: true })
  mkdirSync(dir, { recursive: true })
  return dir
}

function settings(overrides: Partial<GatewaySettings> = {}, dir = scenarioDir()): GatewaySettings {
  return {
    mode: 'active', onFailure: 'claude_status_quo', python: '/usr/bin/python3', bridge: MOCK,
    config: join(dir, 'gateway.json'), timeoutMs: 1500, problems: [], ...overrides,
  }
}

function readJsonl(path: string): any[] {
  return existsSync(path) ? readFileSync(path, 'utf8').split('\n').filter(Boolean).map(l => JSON.parse(l)) : []
}

let mid = 1
function ctxFor(text: string, extra: Record<string, unknown> = {}, from: any = { id: OWNER_ID, is_bot: false, first_name: 'Kais', username: 'kais_test' }) {
  const message = { message_id: mid++, date: 1_800_000_000, chat: { id: from.id, type: 'private' }, from, text, ...extra }
  return { from, chat: message.chat, message }
}

function fakeBot(fail = false) {
  const sent: Array<{ chatId: string; text: string }> = []
  return {
    sent,
    api: {
      sendMessage: async (chatId: string, text: string) => {
        if (fail) throw new Error('Telegram nicht erreichbar (Test)')
        sent.push({ chatId, text })
        return { message_id: 1 }
      },
    },
  }
}

function captureStderr(): { lines: () => any[]; restore: () => void } {
  const original = process.stderr.write.bind(process.stderr)
  const chunks: string[] = []
  process.stderr.write = ((chunk: any) => {
    chunks.push(String(chunk))
    return true
  }) as typeof process.stderr.write
  return {
    lines: () => chunks.join('').split('\n').filter(l => l.startsWith('aria-gateway: ')).map(l => JSON.parse(l.slice(14))),
    restore: () => { process.stderr.write = original },
  }
}

function validResponse(overrides: Record<string, unknown> = {}): Record<string, unknown> {
  return {
    protocol: 1, handling: 'reply', code: 'COMPLETED', job_id: 'tg-1-1', backend: 'codex', status: 'completed',
    reply_text: 'ok', forward: null, flags: [], shadow: false, planned_handling: null, privacy: 'public', delivered: false,
    ...overrides,
  }
}

async function forwardFixture(text = 'Hallo') {
  const ctx = ctxFor(text)
  const request = await buildRequest('execute', { bot: fakeBot(), ctx, text, imagePath: undefined, attachment: undefined })
  const expected = channelParams(ctx, text, undefined, undefined)
  const forward = {
    action: 'FORWARD_TO_CLAUDE_CHANNEL', method: 'notifications/claude/channel', job_id: `tg-${request.chat_id}-${request.message_id}`,
    params: JSON.parse(JSON.stringify(expected)),
    clearance: {
      v: 1, job_id: `tg-${request.chat_id}-${request.message_id}`, backend: 'claude', privacy: 'unknown', context_digest: 'a'.repeat(64),
      sender_id: request.sender_id, chat_id: request.chat_id, issued_at: 1, expires_at: 2, nonce: 'b'.repeat(32), mac: 'c'.repeat(64),
    },
  }
  const response = validResponse({ handling: 'forward_to_claude_channel', code: 'FORWARD_ISSUED', job_id: forward.job_id, backend: 'claude', forward, reply_text: null, privacy: 'unknown' })
  return { ctx, request, expected, response }
}

// ------------------------------------------------------------------------------------------
describe('readSettings', () => {
  test('leere Umgebung: off, claude_status_quo, keine Probleme', () => {
    const s = readSettings({})
    expect([s.mode, s.onFailure, s.problems]).toEqual(['off', 'claude_status_quo', []])
  })

  test('shadow/active ohne Bridge-Pfade: Probleme gemeldet, Python-Default /usr/bin/python3', () => {
    const s = readSettings({ ARIA_GATEWAY_MODE: 'shadow' })
    expect(s.mode).toBe('shadow')
    expect(s.python).toBe('/usr/bin/python3')
    expect(s.problems.sort()).toEqual(['BRIDGE_MISSING', 'CONFIG_MISSING'])
    expect(s.timeoutMs).toBe(3000)
    expect(readSettings({ ARIA_GATEWAY_MODE: 'active', ARIA_GATEWAY_BRIDGE: '/b', ARIA_GATEWAY_CONFIG: '/c' }).timeoutMs).toBe(15_000)
  })

  test('ungültiger Modus fällt auf off (Prod-Verhalten) zurück', () => {
    for (const value of ['actve', 'ACTIVE', 'on', '1', ' shadow']) {
      const s = readSettings({ ARIA_GATEWAY_MODE: value })
      expect([value, s.mode, s.problems.includes('MODE_INVALID')]).toEqual([value, 'off', true])
    }
  })

  test('Ausfallregel: Default claude_status_quo, ungültig wird block (strenger)', () => {
    expect(readSettings({ ARIA_GATEWAY_MODE: 'active' }).onFailure).toBe('claude_status_quo')
    expect(readSettings({ ARIA_GATEWAY_MODE: 'active', ARIA_GATEWAY_ON_FAILURE: 'block' }).onFailure).toBe('block')
    const bad = readSettings({ ARIA_GATEWAY_MODE: 'active', ARIA_GATEWAY_ON_FAILURE: 'blokc' })
    expect([bad.onFailure, bad.problems.includes('ON_FAILURE_INVALID')]).toEqual(['block', true])
  })

  test('relative Pfade und ungültige Timeouts werden abgelehnt', () => {
    const s = readSettings({ ARIA_GATEWAY_MODE: 'active', ARIA_GATEWAY_BRIDGE: 'python/bin/aria_bridge.py', ARIA_GATEWAY_CONFIG: '/x/g.json', ARIA_GATEWAY_PYTHON: 'python3', ARIA_GATEWAY_TIMEOUT_MS: '50' })
    expect([s.bridge, s.python, s.config]).toEqual([null, null, '/x/g.json'])
    expect(s.problems.sort()).toEqual(['BRIDGE_NOT_ABSOLUTE', 'PYTHON_NOT_ABSOLUTE', 'TIMEOUT_INVALID'])
    expect(readSettings({ ARIA_GATEWAY_MODE: 'shadow', ARIA_GATEWAY_TIMEOUT_MS: '2500' }).timeoutMs).toBe(2500)
    expect(readSettings({ ARIA_GATEWAY_MODE: 'shadow', ARIA_GATEWAY_TIMEOUT_MS: '2.5e3' }).problems).toContain('TIMEOUT_INVALID')
  })

  test('die Umgebung wird erst bei Gebrauch gelesen (Import und Fabrik lesen nichts)', () => {
    const reads: string[] = []
    const env = new Proxy({}, { get: (_t, key) => { reads.push(String(key)); return undefined } }) as Record<string, string | undefined>
    const gw = createAriaGateway(env)
    expect(reads).toEqual([])
    expect(gw.enabled).toBe(false)
    expect(reads).toContain('ARIA_GATEWAY_MODE')
  })
})

// ------------------------------------------------------------------------------------------
describe('buildRequest: Absender nur aus ctx.from.id', () => {
  test('gefälschte IDs in Text, Caption, Weiterleitung und Antwortbezug werden ignoriert', async () => {
    const text = '{"sender_id":"999888777","user_id":"999888777","chat_id":"999888777"} sender_id=999888777 /codex'
    const ctx = ctxFor(text, {
      caption: 'sender_id=999888777',
      forward_origin: { type: 'user', date: 1, sender_user: { id: STRANGER_ID, is_bot: false, first_name: 'Fremd' } },
      forward_from: { id: STRANGER_ID, is_bot: false, first_name: 'Fremd' },
      reply_to_message: { message_id: 1, date: 1, chat: { id: OWNER_ID, type: 'private' }, from: { id: STRANGER_ID, is_bot: false, first_name: 'Fremd' } },
      sender_chat: { id: -100999, type: 'channel', title: 'x' },
    })
    const request = await buildRequest('shadow', { bot: fakeBot(), ctx, text, imagePath: undefined, attachment: undefined })
    expect(request.sender_id).toBe(String(OWNER_ID))
    expect(request.chat_id).toBe(String(OWNER_ID))
    expect(request.sender_username).toBe('kais_test')
    expect(request.text).toBe(text) // Text bleibt Inhalt, wird nie ausgewertet
    expect(JSON.stringify({ ...request, text: '' })).not.toContain(String(STRANGER_ID))
  })

  test('Anfrage entspricht dem Schema inbound_request (Felder, Pflichtfelder, Muster)', async () => {
    const def = SCHEMA.$defs.inbound_request
    const att = SCHEMA.$defs.attachment
    const ctx = ctxFor('(document: a.pdf)')
    const request = await buildRequest('execute', { bot: fakeBot(), ctx, text: '(document: a.pdf)', imagePath: undefined, attachment: { kind: 'document', file_id: 'BQ', size: 0, mime: '', name: 'a.pdf' } })
    expect(Object.keys(request).every(k => k in def.properties)).toBe(true)
    expect(def.required.every((k: string) => k in request)).toBe(true)
    expect(new RegExp(def.properties.sender_id.pattern).test(request.sender_id)).toBe(true)
    expect(new RegExp(def.properties.chat_id.pattern).test(request.chat_id)).toBe(true)
    expect(def.properties.chat_type.enum).toContain(request.chat_type)
    expect(request.attachments).toEqual([{ kind: 'document', file_id: 'BQ', size: 0, name: 'a.pdf' }]) // size 0 bleibt, leere mime entfällt
    expect(request.attachments.every(a => Object.keys(a).every(k => k in att.properties))).toBe(true)
    expect(request.ts).toBe('2027-01-15T08:00:00.000Z')
  })

  test('Foto: größte Auflösung, local_path und sha256 des heruntergeladenen Inhalts', async () => {
    const dir = scenarioDir()
    const path = join(dir, 'photo.jpg')
    writeFileSync(path, Buffer.from([1, 2, 3, 4]))
    const photo = [{ file_id: 'small', file_unique_id: 's', width: 1, height: 1, file_size: 10 }, { file_id: 'large', file_unique_id: 'l', width: 2, height: 2, file_size: 99 }]
    const ctx = ctxFor('(photo)', { photo })
    const withPath = await buildRequest('execute', { bot: fakeBot(), ctx, text: '(photo)', imagePath: path, attachment: undefined })
    expect(withPath.attachments).toEqual([{ kind: 'photo', file_id: 'large', size: 99, local_path: path, sha256: createHash('sha256').update(Buffer.from([1, 2, 3, 4])).digest('hex') }])
    const without = await buildRequest('execute', { bot: fakeBot(), ctx, text: '(photo)', imagePath: undefined, attachment: undefined })
    expect(without.attachments).toEqual([{ kind: 'photo', file_id: 'large', size: 99 }])
  })

  test('unvollständige oder ungültige Identität wird abgelehnt (GatewayInputError)', async () => {
    const bad = [
      { from: undefined, chat: { id: 1, type: 'private' }, message: { message_id: 1, date: 1 } },
      { from: { id: 'abc' }, chat: { id: 1, type: 'private' }, message: { message_id: 1, date: 1 } },
      { from: { id: 1 }, chat: { id: 1, type: 'bogus' }, message: { message_id: 1, date: 1 } },
      { from: { id: 1 }, chat: { id: 1, type: 'private' }, message: { message_id: -1, date: 1 } },
    ]
    for (const ctx of bad) {
      const error = await buildRequest('execute', { bot: fakeBot(), ctx, text: 'x', imagePath: undefined, attachment: undefined }).catch(e => e)
      expect(error).toBeInstanceOf(GatewayInputError)
    }
  })
})

// ------------------------------------------------------------------------------------------
describe('channelParams und Einmal-Modus', () => {
  test('oneShotRemainder folgt commands.py (nur /auto /codex /claude mit Text)', () => {
    expect(oneShotRemainder('/claude hallo welt')).toBe('hallo welt')
    expect(oneShotRemainder('  /CODEX@aria_test_bot   prüfe das  ')).toBe('prüfe das')
    expect(oneShotRemainder('/codex')).toBeNull()
    expect(oneShotRemainder('/status jetzt')).toBeNull()
    expect(oneShotRemainder('hallo /codex x')).toBeNull()
  })

  test('channelParams: Dokument mit Metadaten, Foto nur mit image_path', () => {
    const ctx = ctxFor('x')
    const doc = channelParams(ctx, 'x', undefined, { kind: 'document', file_id: 'f', size: 5, mime: 'text/plain', name: 'n' })
    expect(doc.meta).toEqual({ chat_id: String(OWNER_ID), message_id: String(ctx.message.message_id), user: 'kais_test', user_id: String(OWNER_ID), ts: '2027-01-15T08:00:00.000Z', attachment_kind: 'document', attachment_file_id: 'f', attachment_size: '5', attachment_mime: 'text/plain', attachment_name: 'n' })
    const photo = channelParams(ctx, 'x', '/p.jpg', undefined)
    expect(photo.meta).toEqual({ chat_id: String(OWNER_ID), message_id: String(ctx.message.message_id), user: 'kais_test', user_id: String(OWNER_ID), ts: '2027-01-15T08:00:00.000Z', image_path: '/p.jpg' })
  })
})

// ------------------------------------------------------------------------------------------
describe('validateResponse (Schema response)', () => {
  test('gültige Antworten werden angenommen', async () => {
    expect(validateResponse(validResponse())).not.toBeNull()
    expect(validateResponse(validResponse({ handling: 'shadow_decision', shadow: true, planned_handling: 'reply', reply_text: null, status: null }))).not.toBeNull()
    expect(validateResponse(validResponse({ handling: 'error', code: 'KEY_UNAVAILABLE', job_id: null, backend: null, status: null, reply_text: null, privacy: null }))).not.toBeNull()
    expect(validateResponse((await forwardFixture()).response)).not.toBeNull()
  })

  test('jede Abweichung vom Schema wird abgelehnt', async () => {
    const { response } = await forwardFixture()
    const variants: Array<[string, unknown]> = [
      ['fehlendes Feld', (() => { const r = validResponse(); delete r.flags; return r })()],
      ['Zusatzfeld', validResponse({ trusted: true })],
      ['protocol 2', validResponse({ protocol: 2 })],
      ['delivered true', validResponse({ delivered: true })],
      ['unbekanntes handling', validResponse({ handling: 'teleport' })],
      ['backend falsch', validResponse({ backend: 'gpt' })],
      ['flags kein Array', validResponse({ flags: 'x' })],
      ['shadow kein bool', validResponse({ shadow: 'false' })],
      ['planned shadow_decision', validResponse({ planned_handling: 'shadow_decision' })],
      ['meta Zusatzfeld', { ...response, forward: { ...(response as any).forward, params: { ...(response as any).forward.params, meta: { ...(response as any).forward.params.meta, trusted: 'yes' } } } }],
      ['nonce falsch', { ...response, forward: { ...(response as any).forward, clearance: { ...(response as any).forward.clearance, nonce: 'xyz' } } }],
      ['Array statt Objekt', [validResponse()]],
      ['null', null],
    ]
    for (const [name, value] of variants) expect([name, validateResponse(value)]).toEqual([name, null])
  })
})

// ------------------------------------------------------------------------------------------
describe('decideActive: verweigerte Freigaben kippen nie in eine Weiterleitung', () => {
  test('gültige Weiterleitung mit passender Bindung', async () => {
    const { request, expected, response } = await forwardFixture()
    const verdict = decideActive(request, expected, { ok: true, response: validateResponse(response)! }, 'claude_status_quo')
    expect([verdict.forward, verdict.outcome]).toEqual([true, 'FORWARD'])
  })

  test('reply/blocked/failed/drop/not_intercepted: unter BEIDEN Ausfallregeln nie weiterleiten', async () => {
    const { request, expected } = await forwardFixture()
    for (const handling of NON_FORWARD_HANDLINGS) {
      for (const policy of ['claude_status_quo', 'block'] as const) {
        const r = validateResponse(validResponse({ handling, reply_text: handling === 'drop' ? null : 'x' }))!
        expect([handling, policy, decideActive(request, expected, { ok: true, response: r }, policy).forward]).toEqual([handling, policy, false])
      }
    }
  })

  test('Verweigerung mit beigelegter Weiterleitung, geplanter Verweigerung oder ungültigem Rest: nie weiterleiten', async () => {
    const { request, expected, response } = await forwardFixture()
    const blockedWithForward = validateResponse({ ...response, handling: 'blocked', code: 'X' })!
    expect(decideActive(request, expected, { ok: true, response: blockedWithForward }, 'claude_status_quo').forward).toBe(false)
    const shadowPlannedBlock = validateResponse(validResponse({ handling: 'shadow_decision', shadow: true, planned_handling: 'blocked', reply_text: null }))!
    expect(decideActive(request, expected, { ok: true, response: shadowPlannedBlock }, 'claude_status_quo').forward).toBe(false)
    for (const raw of [{ rawHandling: 'blocked' }, { rawHandling: 'drop' }, { rawPlanned: 'failed' }]) {
      const outcome: BridgeOutcome = { ok: false, code: 'BRIDGE_INVALID_RESPONSE', ...raw }
      const verdict = decideActive(request, expected, outcome, 'claude_status_quo')
      expect([raw, verdict.forward, verdict.reply]).toEqual([raw, false, TEXTS.blocked])
    }
  })

  test('Router-Ausfall: claude_status_quo leitet weiter, block nicht (mit Erklärung)', async () => {
    const { request, expected } = await forwardFixture()
    const failures: BridgeOutcome[] = [
      { ok: false, code: 'BRIDGE_TIMEOUT' }, { ok: false, code: 'BRIDGE_EXIT_NONZERO' }, { ok: false, code: 'BRIDGE_INVALID_JSON' },
      { ok: false, code: 'BRIDGE_INVALID_RESPONSE', rawHandling: 'teleport' },
      { ok: true, response: validateResponse(validResponse({ handling: 'error', code: 'KEY_UNAVAILABLE', reply_text: null }))! },
      { ok: true, response: validateResponse(validResponse({ handling: 'shadow_decision', shadow: true, planned_handling: 'forward_to_claude_channel', reply_text: null }))! },
    ]
    for (const outcome of failures) {
      const quo = decideActive(request, expected, outcome, 'claude_status_quo')
      const block = decideActive(request, expected, outcome, 'block')
      expect([quo.forward, quo.outcome.startsWith('ROUTER_FAILURE:')]).toEqual([true, true])
      expect([block.forward, block.reply]).toEqual([false, TEXTS.routerDown])
    }
  })

  test('Weiterleitung mit falscher Bindung ist ein Router-Ausfall', async () => {
    const { request, expected, response } = await forwardFixture('Hallo Bindung')
    const mutate = (fn: (r: any) => void) => { const r = JSON.parse(JSON.stringify(response)); fn(r); return validateResponse(r)! }
    const cases: Array<[string, any]> = [
      ['FORWARD_CONTENT_MISMATCH', mutate(r => { r.forward.params.content = 'anderer Text' })],
      ['FORWARD_META_MISMATCH', mutate(r => { r.forward.params.meta.user_id = '1' })],
      ['FORWARD_META_MISMATCH', mutate(r => { r.forward.params.meta.image_path = '/x' })],
      ['FORWARD_META_MISMATCH', mutate(r => { delete r.forward.params.meta.message_id })],
      ['FORWARD_SUBJECT_MISMATCH', mutate(r => { r.forward.clearance.sender_id = '1' })],
      ['FORWARD_SUBJECT_MISMATCH', mutate(r => { r.forward.clearance.chat_id = '1' })],
      ['FORWARD_JOB_MISMATCH', mutate(r => { r.forward.job_id = 'tg-x' })],
      ['FORWARD_BACKEND_MISMATCH', mutate(r => { r.forward.clearance.backend = 'codex' })],
    ]
    for (const [code, r] of cases) {
      expect(decideActive(request, expected, { ok: true, response: r }, 'block')).toEqual({ forward: false, reply: TEXTS.routerDown, notice: null, outcome: `ROUTER_FAILURE:${code}`, params: null })
      expect(decideActive(request, expected, { ok: true, response: r }, 'claude_status_quo').forward).toBe(true)
    }
  })

  test('Einmal-Modus: freigegebener Rest statt ganzer Nachricht wird akzeptiert', async () => {
    const { request, expected, response } = await forwardFixture('/claude bitte prüfen')
    const r = JSON.parse(JSON.stringify(response))
    r.forward.params.content = 'bitte prüfen'
    expect(decideActive(request, expected, { ok: true, response: validateResponse(r)! }, 'block').outcome).toBe('FORWARD')
  })

  test('failureVerdict ist die einzige Stelle, an der ein Ausfall weiterleitet', () => {
    expect(failureVerdict('X', 'claude_status_quo')).toEqual({ forward: true, reply: null, notice: null, outcome: 'ROUTER_FAILURE:X', params: null })
    expect(failureVerdict('X', 'block')).toEqual({ forward: false, reply: TEXTS.routerDown, notice: null, outcome: 'ROUTER_FAILURE:X', params: null })
  })
})

// ------------------------------------------------------------------------------------------
describe('runBridgeProcess: echter Prozess mit Mock-Bridge', () => {
  async function run(text: string, overrides: Partial<GatewaySettings> = {}): Promise<{ outcome: BridgeOutcome; dir: string; ms: number }> {
    const dir = scenarioDir()
    const s = settings(overrides, dir)
    const ctx = ctxFor(text)
    const request = await buildRequest('execute', { bot: fakeBot(), ctx, text, imagePath: undefined, attachment: undefined })
    const started = Date.now()
    const outcome = await runBridgeProcess(s, JSON.stringify(request), s.timeoutMs)
    return { outcome, dir, ms: Date.now() - started }
  }

  test('normale Antwort wird geprüft angenommen', async () => {
    const { outcome } = await run('Hallo')
    expect(outcome.ok).toBe(true)
    if (outcome.ok) expect(outcome.response.handling).toBe('forward_to_claude_channel')
  })

  test('Review #12: über die Chunk-Grenze geteilter Umlaut wird korrekt dekodiert (keine Ersatzzeichen)', async () => {
    const { outcome } = await run('[split-umlaut] Tschüss')
    expect(outcome.ok).toBe(true)
    if (!outcome.ok) return
    const content = outcome.response.forward!.params.content
    expect(content).toBe('[split-umlaut] Tschüss')   // ü intakt
    expect(content.includes('�')).toBe(false)    // kein U+FFFD-Ersatzzeichen
  })

  test('Kindprozess: nur PATH in der Umgebung, python -I, cwd /, keine Token-Vererbung', async () => {
    process.env.TELEGRAM_BOT_TOKEN = '000000:TEST_LEAK_CANARY'
    process.env.ARIA_SUPABASE_SERVICE_KEY = 'TEST_LEAK_CANARY'
    try {
      const { outcome } = await run('[env]')
      expect(outcome.ok).toBe(true)
      if (!outcome.ok) return
      const info = JSON.parse(outcome.response.reply_text!)
      expect(info.env.filter((k: string) => k !== 'LC_CTYPE')).toEqual(['PATH'])
      expect(info.isolated).toBe(true)
      expect(info.cwd).toBe('/')
      expect(info.argv[0]).toBe('--config')
    } finally {
      delete process.env.TELEGRAM_BOT_TOKEN
      delete process.env.ARIA_SUPABASE_SERVICE_KEY
    }
  })

  test('Timeout: Prozessgruppe wird getötet, Ergebnis BRIDGE_TIMEOUT ohne Hängen', async () => {
    const { outcome, dir, ms } = await run('[timeout]', { timeoutMs: 400 })
    expect(outcome).toEqual({ ok: false, code: 'BRIDGE_TIMEOUT' })
    expect(ms).toBeLessThan(400 + LIMITS.killGraceMs + 500)
    const start = readJsonl(join(dir, 'events.jsonl')).find(e => e.event === 'start')
    expect(start).toBeDefined()
    let alive = true
    try { process.kill(start.pid, 0) } catch { alive = false }
    expect(alive).toBe(false)
  })

  test('Review #9: Abbruch schickt ERST SIGTERM (Bridge kann aufräumen), erst danach SIGKILL', async () => {
    const { outcome, dir } = await run('[trap-term]', { timeoutMs: 300 })
    expect(outcome).toEqual({ ok: false, code: 'BRIDGE_TIMEOUT' })
    // Die Bridge hat SIGTERM abgefangen und protokolliert -> es war KEIN sofortiges SIGKILL
    // (SIGKILL ist nicht abfangbar). Genau so stoppt die echte Bridge ihren Codex-Scope.
    const term = readJsonl(join(dir, 'events.jsonl')).find(e => e.event === 'sigterm')
    expect(term).toBeDefined()
  })

  test('Absturz, Signal, kaputtes JSON, zwei Zeilen, ungültige Antwort, Ausgabelimits', async () => {
    const cases: Array<[string, Record<string, unknown>]> = [
      ['[crash]', { ok: false, code: 'BRIDGE_EXIT_NONZERO' }],
      ['[kill]', { ok: false, code: 'BRIDGE_SIGNALED' }],
      ['[garbage]', { ok: false, code: 'BRIDGE_INVALID_JSON' }],
      ['[twolines]', { ok: false, code: 'BRIDGE_INVALID_JSON' }],
      ['[invalid]', { ok: false, code: 'BRIDGE_INVALID_RESPONSE', rawHandling: 'teleport' }],
      ['[extra-field] [blocked]', { ok: false, code: 'BRIDGE_INVALID_RESPONSE', rawHandling: 'blocked' }],
      ['[bigout]', { ok: false, code: 'BRIDGE_OUTPUT_LIMIT' }],
      ['[stderr-flood]', { ok: false, code: 'BRIDGE_STDERR_LIMIT' }],
    ]
    for (const [text, expected] of cases) expect([text, (await run(text)).outcome]).toEqual([text, expected])
  })

  // Prüft nur das Ergebnis. Den stdin-Fehlerpfad übt dieser Test unter bun 1.3.13 NICHT aus: bun meldet
  // bei einem nicht lesenden Kindprozess kein 'error' auf stdin (Probe bis 3 MB). Siehe MUTATIONSPROBEN.md T16.
  test('Bridge antwortet ohne stdin zu lesen: die gültige Antwort zählt', async () => {
    const dir = scenarioDir()
    const s = settings({ config: join(dir, 'noread.json') }, dir)
    const big = 'x'.repeat(300_000) // größer als der Pipe-Puffer, damit das Schreiben scheitert
    const ctx = ctxFor(big)
    const request = await buildRequest('execute', { bot: fakeBot(), ctx, text: big, imagePath: undefined, attachment: undefined })
    const outcome = await runBridgeProcess(s, JSON.stringify(request), 3000)
    expect(outcome.ok).toBe(true)
    if (outcome.ok) expect([outcome.response.handling, outcome.response.code]).toEqual(['error', 'CONFIG_UNAVAILABLE'])
  })

  test('nicht startbarer Interpreter und fehlende Konfiguration: sofortiger Fehler, kein Hängen', async () => {
    const missing = await run('Hallo', { python: '/nonexistent/python3' })
    expect(missing.outcome).toEqual({ ok: false, code: 'BRIDGE_SPAWN_FAILED' })
    expect(missing.ms).toBeLessThan(LIMITS.killGraceMs + 500)
    expect((await run('Hallo', { bridge: null })).outcome).toEqual({ ok: false, code: 'BRIDGE_NOT_CONFIGURED' })
  })
})

// ------------------------------------------------------------------------------------------
describe('createAriaGateway: Modi, Nebenläufigkeit, Dedup, Zustellfehler', () => {
  let dir: string
  let env: Record<string, string>
  beforeEach(() => {
    dir = scenarioDir()
    env = { ARIA_GATEWAY_BRIDGE: MOCK, ARIA_GATEWAY_CONFIG: join(dir, 'gateway.json'), ARIA_GATEWAY_TIMEOUT_MS: '1500' }
  })
  const input = (bot: any, text: string, extra: Record<string, unknown> = {}) => {
    const ctx = ctxFor(text, extra)
    return { bot, ctx, text, imagePath: undefined, attachment: undefined }
  }
  const maxParallel = (events: any[]) => {
    let current = 0
    let max = 0
    for (const e of [...events].sort((a, b) => a.t - b.t)) {
      current += e.event === 'start' ? 1 : -1
      max = Math.max(max, current)
    }
    return max
  }

  test('off: enabled=false, inbound startet keinen Prozess', async () => {
    const gw = createAriaGateway({ ...env })
    expect(gw.enabled).toBe(false)
    expect((await gw.inbound(input(fakeBot(), 'Hallo'))).forward).toBe(true)
    await gw.settled()
    expect(existsSync(join(dir, 'requests.jsonl'))).toBe(false)
  })

  test('shadow: liefert sofort true, auch wenn die Bridge hängt; Ausfall nur im Protokoll', async () => {
    const cap = captureStderr()
    try {
      const gw = createAriaGateway({ ...env, ARIA_GATEWAY_MODE: 'shadow', ARIA_GATEWAY_TIMEOUT_MS: '600' })
      const started = Date.now()
      expect((await gw.inbound(input(fakeBot(), '[timeout] Hallo'))).forward).toBe(true)
      expect(Date.now() - started).toBeLessThan(100)
      await gw.settled()
      const entry = cap.lines().find(l => l.phase === 'decision')
      expect([entry.mode, entry.ok, entry.failure, entry.forwarded, entry.sender_id]).toEqual(['shadow', false, 'BRIDGE_TIMEOUT', true, String(OWNER_ID)])
    } finally {
      cap.restore()
    }
  })

  test('shadow: höchstens 3 Bridge-Prozesse, Überlauf wird übersprungen (BRIDGE_BUSY), Weiterleitung immer', async () => {
    const cap = captureStderr()
    try {
      const gw = createAriaGateway({ ...env, ARIA_GATEWAY_MODE: 'shadow' })
      const results = await Promise.all(Array.from({ length: 6 }, (_, i) => gw.inbound(input(fakeBot(), `[slow] Nachricht ${i}`))))
      expect(results.map(r => r.forward)).toEqual(Array(6).fill(true))
      await gw.settled()
      const entries = cap.lines().filter(l => l.phase === 'decision')
      expect(entries.length).toBe(6)
      expect(entries.filter(e => e.failure === 'BRIDGE_BUSY').length).toBe(3)
      expect(maxParallel(readJsonl(join(dir, 'events.jsonl')))).toBeLessThanOrEqual(3)
    } finally {
      cap.restore()
    }
  })

  test('active: 10 parallele Nachrichten, Warteschlange statt Ausfall, höchstens 3 Prozesse, jede Antwort an den richtigen Chat', async () => {
    const cap = captureStderr()
    try {
      const gw = createAriaGateway({ ...env, ARIA_GATEWAY_MODE: 'active', ARIA_GATEWAY_TIMEOUT_MS: '8000' })
      const bot = fakeBot()
      const inputs = Array.from({ length: 10 }, (_, i) => input(bot, i % 2 === 0 ? `[slow] [codex] Auftrag ${i}` : `[slow] Frage ${i}`))
      const results = await Promise.all(inputs.map(x => gw.inbound(x)))
      expect(results.map(r => r.forward)).toEqual(inputs.map((_, i) => i % 2 !== 0))
      expect(maxParallel(readJsonl(join(dir, 'events.jsonl')))).toBeLessThanOrEqual(3)
      expect(readJsonl(join(dir, 'requests.jsonl')).length).toBe(10)
      expect(bot.sent.map(s => s.text).sort()).toEqual(inputs.filter((_, i) => i % 2 === 0).map(x => `MOCK_CODEX_RESPONSE für Nachricht ${x.ctx.message.message_id}`).sort())
      expect(cap.lines().filter(l => l.outcome?.startsWith('ROUTER_FAILURE')).length).toBe(0)
    } finally {
      cap.restore()
    }
  })

  test('active: Wartezeit in der Warteschlange läuft ab -> BRIDGE_QUEUE_TIMEOUT -> Ausfallregel', async () => {
    const cap = captureStderr()
    try {
      const liveEnv: Record<string, string> = { ...env, ARIA_GATEWAY_MODE: 'active', ARIA_GATEWAY_TIMEOUT_MS: '1500', ARIA_GATEWAY_ON_FAILURE: 'block' }
      const gw = createAriaGateway(liveEnv)
      const runners = [0, 1, 2].map(i => gw.inbound(input(fakeBot(), `[timeout] belegt ${i}`)))
      await Bun.sleep(150) // alle drei Plätze belegt
      liveEnv.ARIA_GATEWAY_TIMEOUT_MS = '200' // Frist des vierten Aufrufs kürzer als die Laufzeit der Belegung
      const bot = fakeBot()
      expect((await gw.inbound(input(bot, '[codex] wartet'))).forward).toBe(false)
      expect(bot.sent.map(s => s.text)).toEqual([TEXTS.routerDown])
      await Promise.all(runners)
      const outcomes = cap.lines().filter(l => l.phase === 'decision').map(l => l.outcome)
      expect(outcomes.filter(o => o === 'ROUTER_FAILURE:BRIDGE_QUEUE_TIMEOUT').length).toBe(1)
      expect(outcomes.filter(o => o === 'ROUTER_FAILURE:BRIDGE_TIMEOUT').length).toBe(3)
    } finally {
      cap.restore()
    }
  })

  test('active: doppelte message_id wird nur einmal verarbeitet (auch bei Router-Ausfall)', async () => {
    const gw = createAriaGateway({ ...env, ARIA_GATEWAY_MODE: 'active' })
    const first = input(fakeBot(), 'Hallo doppelt')
    expect((await gw.inbound(first)).forward).toBe(true)
    expect((await gw.inbound({ ...first })).forward).toBe(false)
    expect(readJsonl(join(dir, 'requests.jsonl')).length).toBe(1)
    const failing = input(fakeBot(), '[crash] doppelt bei Ausfall')
    expect((await gw.inbound(failing)).forward).toBe(true) // claude_status_quo
    expect((await gw.inbound({ ...failing })).forward).toBe(false)
    expect(readJsonl(join(dir, 'requests.jsonl')).length).toBe(2)
  })

  test('active: Sperre bleibt Sperre, auch wenn das Senden der Erklärung scheitert', async () => {
    const cap = captureStderr()
    try {
      const gw = createAriaGateway({ ...env, ARIA_GATEWAY_MODE: 'active' })
      expect((await gw.inbound(input(fakeBot(true), '[blocked] vertraulich'))).forward).toBe(false)
      expect((await gw.inbound(input(fakeBot(true), '[failed] codex'))).forward).toBe(false)
      expect((await gw.inbound(input(fakeBot(true), '[codex] antwort'))).forward).toBe(false)
      const entries = cap.lines().filter(l => l.phase === 'decision')
      expect(entries.map(e => [e.outcome, e.reply_sent, e.forwarded])).toEqual([['BLOCKED', false, false], ['FAILED', false, false], ['REPLY', false, false]])
    } finally {
      cap.restore()
    }
  })

  test('active: lange Codex-Antwort wird in Telegram-Teile zu höchstens 4096 Zeichen zerlegt', async () => {
    const gw = createAriaGateway({ ...env, ARIA_GATEWAY_MODE: 'active' })
    const bot = fakeBot()
    expect((await gw.inbound(input(bot, '[long-reply]'))).forward).toBe(false)
    expect(bot.sent.map(s => s.text.length)).toEqual([4096, 4096, 808])
  })

  test('Konfigurationsprobleme werden einmal gemeldet; ohne Bridge gilt die Ausfallregel', async () => {
    const cap = captureStderr()
    try {
      const quo = createAriaGateway({ ARIA_GATEWAY_MODE: 'active' })
      expect((await quo.inbound(input(fakeBot(), 'a'))).forward).toBe(true)
      expect((await quo.inbound(input(fakeBot(), 'b'))).forward).toBe(true)
      const block = createAriaGateway({ ARIA_GATEWAY_MODE: 'active', ARIA_GATEWAY_ON_FAILURE: 'block' })
      const bot = fakeBot()
      expect((await block.inbound(input(bot, 'c'))).forward).toBe(false)
      expect(bot.sent.map(s => s.text)).toEqual([TEXTS.routerDown])
      const configLines = cap.lines().filter(l => l.phase === 'config')
      expect(configLines.length).toBe(2) // je Instanz einmal
      expect(configLines[0].problems.sort()).toEqual(['BRIDGE_MISSING', 'CONFIG_MISSING'])
      const off = createAriaGateway({ ARIA_GATEWAY_ON_FAILURE: 'blokc' })
      expect(off.enabled).toBe(false)
      expect(cap.lines().filter(l => l.phase === 'config').length).toBe(2) // off: keine Ausgabe (Prod-Verhalten)
    } finally {
      cap.restore()
    }
  })
})
