import { z } from 'zod';
import { defineTool, } from '../toolDefinition.js';
import { AgentToolNames } from './agentToolNames.js';
/**
 * GetRelatedTestRunsDefinition - Tool definition for fetching and comparing test runs of the same test.
 */
export const getRelatedTestRunsParamsSchema = z.object({
    test_run_id: z.string().optional().meta({
        description: 'Test run ID to find related runs for. Provide either test_run_id or test_id. ',
    }),
    test_id: z
        .string()
        .optional()
        .meta({
        description: 'Test ID (invariant) to find related runs for. Provide either test_id or test_run_id. ' +
            'Use this when you have the test ID but not a specific test run ID (e.g. for locally-triggered runs).',
    }),
    filter_status: z.enum(['passed', 'failed', 'all']).optional().meta({
        description: 'Filter runs by status. "passed" returns only passing runs, "failed" returns only failing runs, "all" returns all runs. Default: all',
    }),
    limit: z.number().optional().meta({
        description: 'Maximum number of runs to return. Default: 10. Maximum: 50.',
    }),
    include_current: z.boolean().optional().meta({
        description: 'Whether to include the current test run in results. Default: false',
    }),
    time_range: z.enum(['recent', 'day', 'week', 'month']).optional().meta({
        description: 'Time range to filter runs. "recent" returns most recent runs regardless of time, "day" returns runs from last 24 hours, "week" from last 7 days, "month" from last 30 days. Default: recent',
    }),
    compare_same_browser: z.boolean().optional().meta({
        description: 'If true, only returns runs that used the same browser as the current run. Useful for apples-to-apples comparison. Only applies to browser tests (ignored for API/mobile). Default: false',
    }),
    compare_same_environment: z.boolean().optional().meta({
        description: 'If true, only returns runs that used the same environment as the current run. Useful for isolating environment-specific issues. Requires test_run_id. Default: true',
    }),
    compare_same_scenario: z.boolean().optional().meta({
        description: 'If true, only returns runs that used the same scenario (data table row) as the current run. Useful for isolating scenario-specific failures. Requires test_run_id. Default: true',
    }),
    sort_by: z.enum(['time', 'duration', 'status']).optional().meta({
        description: 'How to sort the results. "time" sorts by start time (newest first), "duration" sorts by execution duration, "status" groups by status. Default: time',
    }),
});
// Simplified test run summary - only essential fields
export const testRunSummarySchema = z.object({
    testRunId: z.string(),
    testVariantId: z.string().optional(),
    status: z.string(),
    normalizedStatus: z.enum(['passed', 'failed', 'other']),
    startTime: z.string().optional(),
    durationMs: z.number().optional(),
    durationFormatted: z.string().optional(),
    browser: z.string().optional(),
    planId: z.string().optional(),
    environmentId: z.string().optional(),
    scenarioId: z.string().optional(),
    failureReason: z.string().optional(),
    isCurrent: z.boolean().optional(),
    isNewVersion: z.boolean().optional(),
    relativeTime: z.string().optional(),
});
// Simplified insights - only actionable data
export const comparisonInsightsSchema = z.object({
    totalRuns: z.number(),
    passedRuns: z.number(),
    failedRuns: z.number(),
    passRate: z.number(),
    lastPassedRun: testRunSummarySchema.optional(),
    lastFailedRun: testRunSummarySchema.optional(),
    lastPassedRunSameVersion: testRunSummarySchema.optional(),
    currentVersionEverPassed: z.boolean().optional(),
    avgDurationMs: z.number().optional(),
    avgDurationFormatted: z.string().optional(),
    isFlaky: z.boolean(),
    flakinessNote: z.string().optional(),
    consecutiveFailures: z.number().optional(),
    consecutivePasses: z.number().optional(),
    failureReasonBreakdown: z
        .array(z.object({
        reason: z.string(),
        count: z.number(),
        percentage: z.number(),
    }))
        .optional(),
    browserBreakdown: z
        .array(z.object({
        browser: z.string(),
        passRate: z.number(),
        runCount: z.number(),
    }))
        .optional()
        .meta({ description: 'Browser breakdown - only included for browser tests (not API/mobile tests)' }),
    versionBreakdown: z
        .array(z.object({
        variantId: z.string(),
        passRate: z.number(),
        runCount: z.number(),
        firstSeen: z.string().optional(),
        lastSeen: z.string().optional(),
    }))
        .optional(),
    testWasModified: z.boolean().optional(),
});
// Current run context includes a bit more detail
export const currentRunContextSchema = z.object({
    testRunId: z.string(),
    testVariantId: z.string().optional(),
    testName: z.string().optional(),
    testType: z.enum(['browser', 'api', 'mobile', 'performance', 'unknown']).optional().meta({
        description: 'The type of test (browser, api, mobile, etc.)',
    }),
    status: z.string(),
    normalizedStatus: z.enum(['passed', 'failed', 'other']),
    startTime: z.string().optional(),
    durationMs: z.number().optional(),
    durationFormatted: z.string().optional(),
    browser: z.string().optional().meta({ description: 'Browser used - only for browser tests' }),
    planId: z.string().optional(),
    environmentId: z.string().optional().meta({ description: 'Environment ID from the deployment parameters' }),
    scenarioId: z.string().optional().meta({ description: 'Scenario ID (data table row) used in this run' }),
    failureReason: z.string().optional(),
    failureSummary: z.string().optional(),
});
export const getRelatedTestRunsResponseSchema = z.object({
    testId: z.string(),
    currentRun: currentRunContextSchema.optional(),
    previousRuns: z.array(testRunSummarySchema),
    insights: comparisonInsightsSchema,
    note: z.string().optional(),
});
export const GetRelatedTestRunsToolDefinition = defineTool({
    name: AgentToolNames.GetRelatedTestRuns,
    description: `Retrieves and analyzes historical test runs of the same test for comparison and pattern detection.

Provide either test_run_id or test_id to identify the test:
- test_run_id: looks up the test run and derives the test identity; includes currentRun details in the response
- test_id: uses the test ID (invariant) directly; no currentRun in the response

Use this tool to:
- Find the last passing run to compare against a failure
- Detect if a test is flaky (alternating pass/fail)
- Identify when a test started failing (regression detection)
- Compare performance/timing across runs
- Analyze patterns in test failures

The tool provides comparison insights including aggregate pass rates, flakiness detection,
duration statistics, and breakdowns by failure reason, browser, and version. Each run summary includes **testRunId** for correlating with per-run tools (screenshots, artifacts, test run info).

**Analyzing streaks and trends:** **consecutiveFailures** and aggregate stats are not a substitute for reading **failureReason** on **each** returned run (and **failureSummary** / **failureReason** on **currentRun** when present). Multiple consecutive failures can have **different** underlying causes — use **insights.failureReasonBreakdown** when present and widen **time_range** (week/month) and **limit** (up to max) so earlier runs with different errors are included before claiming a single root cause across history.`,
    argumentsSchema: getRelatedTestRunsParamsSchema,
    responseSchema: getRelatedTestRunsResponseSchema,
});
//# sourceMappingURL=GetRelatedTestRunsDefinition.js.map