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

const controllerSource = readFileSync(new URL("../src/features/chat/useChatStreamingController.ts", import.meta.url), "utf8")
const composerSource = readFileSync(new URL("../src/features/chat/ChatComposer.tsx", import.meta.url), "utf8")
const mockSource = readFileSync(new URL("../src/lib/mock-desktop-api.ts", import.meta.url), "utf8")

test("chat streaming controller exposes cancelActiveStream and ignores later events", () => {
  assert.match(controllerSource, /cancelActiveStream/)
  assert.match(controllerSource, /desktopApi\.chat\.cancelStream/)
  assert.match(controllerSource, /stoppedRequestIdsRef/)
  assert.match(controllerSource, /event\.type === "cancelled"/)
})

test("chat streaming controller scopes preparing cancellation per submission", () => {
  assert.match(controllerSource, /cancelledSubmissionIdsRef/)
  assert.match(controllerSource, /pendingSubmissionIdRef/)
  assert.doesNotMatch(controllerSource, /preStreamCancelRequestedRef/)
})

test("chat streaming controller clears stopped request ids on terminal events", () => {
  assert.match(controllerSource, /stoppedRequestIdsRef\.current\.delete\(event\.requestId\)/)
})

test("composer can submit a stop action while sending", () => {
  assert.match(composerSource, /onCancel/)
  assert.match(composerSource, /type=\{sending \? "button" : "submit"\}/)
  assert.match(composerSource, /onClick=\{sending \? onCancel : undefined\}/)
})

test("mock desktop API cancels pending stream timers", () => {
  assert.match(mockSource, /mockChatStreamTimers/)
  assert.match(mockSource, /cancelStream/)
  assert.match(mockSource, /window\.clearTimeout/)
})
