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

const ipcSource = readFileSync(new URL("../src/main/ipc.ts", import.meta.url), "utf8")
const indexSource = readFileSync(new URL("../src/main/index.ts", import.meta.url), "utf8")

test("desktop IPC wires tasks:list-by-date to TaskPanelService", () => {
  assert.match(ipcSource, /taskPanelService\.listByDate\(date\)/)
  assert.doesNotMatch(ipcSource, /tasksListByDate,\s*async \(\) => \[\]/)
  assert.match(indexSource, /new TaskPanelService\(systemSummary\.userDataPath\)/)
})

test("workspace-entry success paths archive xhs and douyin executions without throwing", () => {
  assert.match(ipcSource, /recordWorkspaceTaskPanelExecution/)
  assert.match(ipcSource, /xiaohongshu\|xhs\|小红书/)
  assert.match(ipcSource, /douyin\|抖音\|tiktok/)
})

test("workspace-entry task panel matching includes zhihu expert executions", () => {
  assert.match(ipcSource, /zhihu\|知乎/)
  assert.match(ipcSource, /知乎专家/)
})

test("non-workspace expert chat completions are archived to the task panel", () => {
  const firstChatSendIndex = ipcSource.indexOf('reason: "chat-send"')
  const nonWorkspaceChatSendIndex = ipcSource.indexOf('reason: "chat-send"', firstChatSendIndex + 1)
  const nonWorkspaceChatSendBlock = ipcSource.slice(nonWorkspaceChatSendIndex, ipcSource.indexOf("return { ...result", nonWorkspaceChatSendIndex))
  assert.match(nonWorkspaceChatSendBlock, /recordWorkspaceTaskPanelExecution\(\{[\s\S]*projectId: preparedExecution\.sessionState\.projectId/)

  const nonWorkspaceStreamIndex = ipcSource.indexOf('reason: "chat-stream"')
  const nonWorkspaceCompletedBlock = ipcSource.slice(
    ipcSource.indexOf("onCompleted:", nonWorkspaceStreamIndex),
    ipcSource.indexOf("onError:", nonWorkspaceStreamIndex)
  )
  assert.match(nonWorkspaceCompletedBlock, /recordWorkspaceTaskPanelExecution\(\{[\s\S]*projectId: preparedExecution\.sessionState\.projectId/)
})

test("task panel expert matching prioritizes project id before filesystem path", () => {
  assert.match(ipcSource, /const normalizedProjectId = projectId\.trim\(\)\.toLowerCase\(\)/)
  assert.match(ipcSource, /const projectBaseName = path\.basename\(projectRoot\)\.toLowerCase\(\)/)
  assert.match(ipcSource, /isXhsProject\(normalizedProjectId\)/)
  assert.match(ipcSource, /isDouyinProject\(normalizedProjectId\)/)
  assert.doesNotMatch(ipcSource, /`\$\{projectId\} \$\{path\.basename\(projectRoot\)\} \$\{projectRoot\}`/)
})
