import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { Agent, fetch } from 'undici';

const root = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
for (const line of fs.readFileSync(path.join(root, '.env'), 'utf8').split('\n')) {
  const t = line.trim();
  if (!t || t.startsWith('#')) continue;
  const i = t.indexOf('=');
  if (i < 0) continue;
  if (!process.env[t.slice(0, i)]) process.env[t.slice(0, i)] = t.slice(i + 1);
}

const secret = process.env.TKMIND_SERVER__SECRET_KEY ?? 'local-dev-secret';
const base = process.env.TKMIND_API_TARGET ?? 'https://127.0.0.1:18006';
const dispatcher = new Agent({ connect: { rejectUnauthorized: false } });

async function api(pathname, body) {
  const res = await fetch(`${base}${pathname}`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', 'X-Secret-Key': secret },
    body: JSON.stringify(body),
    dispatcher,
  });
  const text = await res.text();
  return { status: res.status, text };
}

const start = await api('/agent/start', {
  working_dir: process.env.VITE_TKMIND_WORKING_DIR || '/Users/john/Project/tkmind_go',
});
console.log('start', start.status);
const session = JSON.parse(start.text);
const sessionId = session.id;
console.log('session', sessionId);

for (const [provider, model] of [
  ['custom_tkmind_relay_deepseek', 'deepseek-chat'],
  ['custom_relay_buyer_deepseek', 'deepseek-chat'],
]) {
  await api('/agent/update_provider', { session_id: sessionId, provider, model });
  const reqId = crypto.randomUUID();
  const userMessage = {
    role: 'user',
    created: Date.now(),
    content: [{ type: 'text', text: 'say hi in one word' }],
    metadata: { userVisible: true, agentVisible: true },
  };
  const reply = await fetch(`${base}/reply`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', 'X-Secret-Key': secret },
    body: JSON.stringify({
      session_id: sessionId,
      chat_request_id: reqId,
      user_message: userMessage,
    }),
    dispatcher,
  });
  console.log(`\n== ${provider} / ${model} == status ${reply.status}`);
  const reader = reply.body.getReader();
  const dec = new TextDecoder();
  let buf = '';
  for (let i = 0; i < 30; i += 1) {
    const { done, value } = await reader.read();
    if (done) break;
    buf += dec.decode(value);
    if (/\"type\":\"Error\"|Server error|10003|500 Internal/.test(buf)) break;
    if (/\"type\":\"Finish\"/.test(buf)) break;
  }
  console.log(buf.slice(0, 1200));
}
