import { z } from "zod";
import { getLogger } from "../../../../util/logger.js";
import { sendUserMessageChannel } from "../../../state-machine/helpers/peer.js";
import { createToolFactory, ToolCategory, PermissionLevel } from "../types.js";
/**
 * endTestRun - Ends the current test run and reports results.
 *
 * This tool:
 * 1. Reconciles any incomplete test cases (sets their final status)
 * 2. Sends test_run_end message to UI with status
 * 3. Clears test run context
 *
 * Only accessible to the TEST subagent (ToolCategory.TEST).
 */
export const endTestRunToolFactory = createToolFactory("endTestRun", ({ clark, services, }) => {
    const logger = getLogger();
    return {
        description: `
End the current test run and report results.

**IMPORTANT**: You MUST call this tool when you have finished testing.

Call this tool when:
- All test cases have been executed
- A critical error prevents further testing
- You've verified the key functionality

The status should reflect the overall test outcome:
- "completed" - All tests passed or the key functionality works
- "failed" - Tests found issues or critical errors occurred
`,
        category: ToolCategory.TEST,
        defaultPermission: PermissionLevel.ALLOW,
        inputSchema: z.object({
            status: z
                .enum(["completed", "failed"])
                .describe("Final status of the test run"),
            summary: z
                .string()
                .describe("Brief summary of test results (1-2 sentences). Example: 'All 5 test steps passed. Form submission and data display work correctly.'"),
        }),
        execute: async ({ status, summary }) => {
            const testRunId = clark.context.currentTestRunId;
            const testCases = clark.context.currentTestCases;
            const testCaseStatuses = clark.context.testCaseStatuses;
            if (!testRunId) {
                logger.warn(`[TestSubagent] No active test run to end`);
                return {
                    success: false,
                    error: "No active test run to end",
                };
            }
            const sendUserMessage = sendUserMessageChannel(clark, services.chatSessionStore);
            // RECONCILIATION: Finalize any test cases still in not_started or running state
            if (testCases && testCases.length > 0) {
                for (const tc of testCases) {
                    const currentStatus = testCaseStatuses?.get(tc.id) ?? "not_started";
                    if (currentStatus === "not_started" ||
                        currentStatus === "running") {
                        // If overall status is "completed", assume untested/running cases passed
                        // If overall status is "failed", mark incomplete cases as failed
                        const finalStatus = status === "completed" ? "passed" : "failed";
                        // Update local tracking
                        if (testCaseStatuses) {
                            testCaseStatuses.set(tc.id, finalStatus);
                        }
                        // Send update to UI
                        await sendUserMessage({
                            type: "test_case_update",
                            testRunId,
                            testCaseId: tc.id,
                            testCaseStatus: finalStatus,
                            role: "assistant",
                            content: "",
                        });
                        logger.info(`[TestSubagent] Reconciled test case '${tc.id}' to '${finalStatus}' (was '${currentStatus}')`);
                    }
                }
            }
            // Send test_run_end message to UI
            await sendUserMessage({
                type: "test_run_end",
                testRunId,
                testStatus: status,
                summary,
                role: "assistant",
                content: "",
            });
            // Clear test run context
            clark.updateContext({
                currentTestRunId: undefined,
                currentTestCases: undefined,
                testCaseStatuses: undefined,
            });
            // Flush Playwright action logs so they're saved after each test run
            await services.mcpServerManager.flushLog();
            logger.info(`[TestSubagent] Test run ended successfully - ${summary}`);
            return {
                success: true,
                testRunId,
                testStatus: status,
                summary,
            };
        },
        getSummary: (_input, output) => {
            return {
                output: `${output.testStatus ?? "completed"} - ${output.summary ?? "Test run ended"}`,
            };
        },
    };
});
//# sourceMappingURL=end-test-run.js.map