import Testing

@testable import NucleicCore

/// The backend records the run's host `cwd` onto each `host_exec` tool call, so the transcript's
/// in-chat host card can resolve `$PWD` to exactly the directory the command ran in — matching the
/// approval card, which gets the same value from the approval request.
@Suite struct HostExecCwdRecordingTests {
    private let hostExec = MCPApprovalServer.qualifiedHostExecToolName

    /// A host_exec call gets `cwd` recorded on its input for both the started and completed events,
    /// without disturbing the agent-provided fields.
    @Test func recordsCwdOnHostExecCalls() {
        let call = ToolCall(
            toolCallID: "toolu_1", name: hostExec,
            input: ["command": "cd $PWD && swift build", "reason": "macOS build"])

        let started = ClaudeCodeBackend.recordingHostExecCwd(
            .toolCallStarted(call), workdir: "/Users/dev/project")
        guard case .toolCallStarted(let out) = started else { Issue.record("expected started"); return }
        #expect(out.input["cwd"]?.stringValue == "/Users/dev/project")
        #expect(out.input["command"]?.stringValue == "cd $PWD && swift build")
        #expect(out.input["reason"]?.stringValue == "macOS build")

        let completed = ClaudeCodeBackend.recordingHostExecCwd(
            .toolCallCompleted(call), workdir: "/Users/dev/project")
        guard case .toolCallCompleted(let done) = completed else { Issue.record("expected completed"); return }
        #expect(done.input["cwd"]?.stringValue == "/Users/dev/project")
    }

    /// No-op for other tools, when there's no host workdir, and when a `cwd` is already present
    /// (idempotent across the started/completed pair — never overwrites an existing value).
    @Test func leavesOtherCasesUntouched() {
        let bash = ToolCall(toolCallID: "t", name: "Bash", input: ["command": "ls"])
        #expect(ClaudeCodeBackend.recordingHostExecCwd(.toolCallStarted(bash), workdir: "/w")
            == .toolCallStarted(bash))

        let host = ToolCall(toolCallID: "t", name: hostExec, input: ["command": "swift build"])
        #expect(ClaudeCodeBackend.recordingHostExecCwd(.toolCallCompleted(host), workdir: nil)
            == .toolCallCompleted(host))

        let withCwd = ToolCall(
            toolCallID: "t", name: hostExec, input: ["command": "swift build", "cwd": "/original"])
        #expect(ClaudeCodeBackend.recordingHostExecCwd(.toolCallCompleted(withCwd), workdir: "/other")
            == .toolCallCompleted(withCwd))
    }
}
