import { describe, expect, it } from "bun:test"
import { childID } from "../../src/kilo-provider/task-session"
import { VisibleTaskStreams } from "../../src/kilo-provider/visible-task-streams"

describe("childID", () => {
  it("reads session ID from top-level metadata", () => {
    expect(childID({ type: "tool", tool: "task", metadata: { sessionId: "child1" } })).toBe("child1")
  })

  it("reads session ID from state metadata", () => {
    expect(childID({ type: "tool", tool: "task", state: { metadata: { sessionId: "child2" } } })).toBe("child2")
  })

  it("prefers top-level metadata over state metadata", () => {
    expect(
      childID({
        type: "tool",
        tool: "task",
        metadata: { sessionId: "top" },
        state: { metadata: { sessionId: "nested" } },
      }),
    ).toBe("top")
  })

  it("ignores non-task tool parts", () => {
    expect(childID({ type: "tool", tool: "read", state: { metadata: { sessionId: "child3" } } })).toBeUndefined()
  })
})

describe("VisibleTaskStreams", () => {
  it("suspends and restores visible child sessions with provider activity", () => {
    const sent: Array<[string, boolean]> = []
    const streams = new VisibleTaskStreams((id, visible) => sent.push([id, visible]))
    streams.handle({ type: "streamSessionVisible", sessionID: "child", visible: true })
    streams.setActive(false)
    streams.setActive(true)
    streams.handle({ type: "streamSessionVisible", sessionID: "child", visible: false })
    expect(sent).toEqual([
      ["child", true],
      ["child", false],
      ["child", true],
      ["child", false],
    ])
  })

  it("clears visible refs after a webview reload", () => {
    const sent: Array<[string, boolean]> = []
    const streams = new VisibleTaskStreams((id, visible) => sent.push([id, visible]))
    streams.handle({ type: "streamSessionVisible", sessionID: "child", visible: true })
    streams.clear()
    streams.handle({ type: "streamSessionVisible", sessionID: "child", visible: false })
    expect(sent).toEqual([
      ["child", true],
      ["child", false],
      ["child", false],
    ])
  })
})
