import test from "node:test"
import assert from "node:assert/strict"
import { readFileSync } from "node:fs"

const gatewaySource = readFileSync(new URL("../src/index.ts", import.meta.url), "utf8")

test("gateway client cancels local pending run even when remote cancel is unavailable", () => {
  assert.match(gatewaySource, /async cancelChatRun\(runId: string\)/)
  assert.match(gatewaySource, /remoteCancelled: false/)
  assert.match(gatewaySource, /this\.pendingChatRuns\.delete\(runId\)/)
})

test("gateway client only sends cancel RPC when gateway advertises chat cancel", () => {
  assert.match(gatewaySource, /availableMethods.*chat\.cancel/s)
  assert.match(gatewaySource, /this\.request\("chat\.cancel"/)
})

test("gateway client builds completed messages from payload before stream fallback", () => {
  assert.match(gatewaySource, /const completedContent = this\.extractTextCandidate\(message\)/)
  assert.match(gatewaySource, /const fallbackText = fallbackContent \?\? pending\?\.accumulatedText \?\? ""/)
  assert.match(gatewaySource, /const content = completedContent\?\.trim\(\)\s*\?\s*completedContent\s*:\s*fallbackText/s)
  assert.match(gatewaySource, /return reply;/)
})

test("gateway client resolves final replies by payload then history then stream", () => {
  assert.match(gatewaySource, /const reply = this\.buildChatMessage\(runId, payload, ""\)/)
  assert.match(gatewaySource, /if \(reply\.content\.trim\(\)\) \{\s*return reply;?\s*\}/s)
  assert.match(gatewaySource, /const assistant = \[\.\.\.history\]\.reverse\(\)\.find\(\(message\) => message\.role === "assistant" && message\.content\.trim\(\)\)/)
  assert.match(gatewaySource, /return assistant/)
  assert.match(gatewaySource, /if \(pending\?\.accumulatedText\.trim\(\)\) \{\s*return this\.buildAccumulatedChatMessage\(pending\.sessionKey, runId, pending\.accumulatedText\);?\s*\}/s)
  assert.doesNotMatch(gatewaySource, /chooseLongestChatMessage/)
  assert.doesNotMatch(gatewaySource, /selectLongestText/)
})
