/**
 * Direct DeepInfra streaming test — bypasses LangChain entirely.
 * Logs each delta.content with JSON.stringify so spaces are unambiguous.
 *
 * Usage:
 *   DEEPINFRA_API_KEY=$(op read "op://Private/DeepInfra/credential") npx tsx src/test-deepinfra-chunks.ts
 */

export {};

const DEEP_INFRA_URL = 'https://api.deepinfra.com/v1/openai/chat/completions';
const MODEL = 'zai-org/GLM-5';

const apiKey = process.env.DEEPINFRA_API_KEY;
if (!apiKey) {
  console.error('DEEPINFRA_API_KEY is not set');
  process.exit(1);
}

const res = await fetch(DEEP_INFRA_URL, {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${apiKey}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    model: MODEL,
    stream: true,
    messages: [
      { role: 'user', content: 'Write two sentences about ETH price analysis.' },
    ],
  }),
});

if (!res.ok || !res.body) {
  console.error(`HTTP ${res.status}: ${await res.text()}`);
  process.exit(1);
}

const reader = res.body.getReader();
const decoder = new TextDecoder();
let chunkIndex = 0;
let assembled = '';

console.log(`Testing model: ${MODEL}`);
console.log('--- chunks ---');

while (true) {
  const { value, done } = await reader.read();
  if (done) break;

  const text = decoder.decode(value, { stream: true });

  for (const line of text.split('\n')) {
    const trimmed = line.trim();
    if (!trimmed.startsWith('data:')) continue;
    const data = trimmed.slice(5).trimStart();
    if (data === '[DONE]') break;

    let parsed: unknown;
    try {
      parsed = JSON.parse(data);
    } catch {
      continue;
    }

    const choice = (parsed as { choices?: Array<{ delta?: Record<string, unknown> }> })
      ?.choices?.[0];
    const delta = choice?.delta;
    const content = delta?.content as string | undefined;

    if (content !== undefined) {
      const endsSpace = content.endsWith(' ');
      const startsSpace = content.startsWith(' ');
      // Log full delta so we can see all available fields (logprobs, token_ids, etc.)
      console.log(
        `chunk[${chunkIndex++}]: ${JSON.stringify(content)} ` +
        `(len=${content.length}, startsSpace=${startsSpace}, endsSpace=${endsSpace}) ` +
        `delta=${JSON.stringify(delta)}`,
      );
      assembled += content;
    }
  }
}

console.log('--- assembled ---');
console.log(assembled);
