/**
 * Predefined One-Click Command: Test this endpoint
 *
 * Spec order:
 *   skyramp_analyze_changes (combined analyze + discover + recommend)
 *   → Evaluate missing (recommended minus existing)
 *   → Generate missing tests (by type)
 *   → Execute generated tests
 *   → [if existing tests found] Analyze test health → Optional batch execute → Actions
 */
const comprehensivelyTestGivenEndpointSteps = [
    {
        stepIndex: 0,
        title: "Ensure workspace is initialized",
        description: "First check whether the repositoryPath is a git repository by verifying that a .git directory exists at the repo root. If there is no .git directory, do not attempt to initialize a Skyramp workspace and proceed without one. If .git exists, check whether .skyramp/workspace.yml exists. If workspace.yml exists, read it and capture language, framework, outputDir, and api.baseUrl for use in later steps. If workspace.yml does not exist and the user has not declined initialization, call skyramp_initialize_workspace with repositoryPath to create it, then read and capture language, framework, outputDir, and api.baseUrl.",
        toolCall: {
            toolName: "skyramp_initialize_workspace",
            description: "Initialize Skyramp workspace if not already present",
            inputs: {
                workspacePath: { source: "user", paramKey: "repositoryPath" },
            },
        },
        conditionalGuidance: "Follow server-level init rules: (1) Check for .git at repositoryPath — if missing, do not call skyramp_initialize_workspace and proceed without a workspace. (2) If .git exists, check for .skyramp/workspace.yml — if it exists, read it and do not call skyramp_initialize_workspace. (3) If workspace.yml does not exist, call skyramp_initialize_workspace only if the user has not explicitly declined. If the user declines, proceed without a workspace. Always capture language, framework, outputDir, and api.baseUrl for later steps.",
    },
    {
        stepIndex: 1,
        title: "Analyze changes and get recommendations",
        description: "Call skyramp_analyze_changes with repositoryPath and scope from the one-click invocation. It scans endpoints, discovers existing tests, and returns ranked test recommendations along with a stateFile path. The response includes a JSON block with stateFile, sessionId, and a summary (including existingTestCount), plus a ranked recommendations section. Capture the stateFile path and the ranked recommendations for later steps. The full list of existing tests is not in the response — it is stored in the stateFile on disk.",
        toolCall: {
            toolName: "skyramp_analyze_changes",
            description: "Analyze repo, discover tests, and generate ranked recommendations; returns stateFile",
            inputs: {
                repositoryPath: { source: "user", paramKey: "repositoryPath" },
                scope: { source: "literal", value: "full_repo" },
            },
            outputs: ["stateFile", "recommendations"],
        },
        conditionalGuidance: "If endpointURL is provided by the user, note it for use in generation steps. Capture the stateFile path and ranked recommendations from the response. The existing test list is not returned directly — it is embedded in the stateFile and will be used by skyramp_analyze_test_health in step 5.",
    },
    {
        stepIndex: 2,
        title: "Evaluate missing tests",
        description: "Using the ranked recommendations from step 1, determine which test types are missing coverage for the target endpoint. The step 1 response includes an existingTestCount in its summary — if it is 0 for the target endpoint, all recommended types are missing. If existingTestCount > 0, the full existing test list is in the stateFile (it will be processed by skyramp_analyze_test_health in step 5); for now, conservatively treat all recommended types as candidates to generate unless the recommendations explicitly note coverage. Build the list of types to generate in step 3. If all recommended types are already covered, skip steps 3 and 4.",
        conditionalGuidance: "For each recommended type (high priority first, then medium), check whether the recommendations indicate existing coverage for the target endpoint. If not indicated, add the type to the 'generate' list. If existingTestCount from step 1 is 0, all types are missing. If all recommended types have coverage, steps 3 and 4 can be skipped.",
    },
    {
        stepIndex: 3,
        title: "Generate missing tests (by type)",
        description: "IMPORTANT — UI or E2E in missing list: If UI or E2E test types are in the 'missing' list, first search the repository for existing trace files suitable for the target endpoint (look for .zip or .json Skyramp trace files in the repo that reference the endpoint path or URL). If suitable traces are found, use them directly as inputs to skyramp_ui_test_generation (playwrightInput) or skyramp_e2e_test_generation (trace + playwrightInput) — skip trace collection. If no suitable traces exist in the repo, collect them: call skyramp_start_trace_collection (playwright: true, outputDir: absolute path from workspace.yml), have the user interact with the target endpoint in the browser, then call skyramp_stop_trace_collection (playwrightEnabled: true, same outputDir). Use the produced trace file and Playwright zip as inputs for generation.\n\nFor all other types in the 'missing' list, call the corresponding generation tool using endpointURL from the one-click invocation (or api.baseUrl + endpoint path from recommendation), apiSchema, language, framework, and outputDir from workspace.yml. Capture each generated test file path.",
        conditionalGuidance: "Tool mapping by type — smoke: skyramp_smoke_test_generation, contract: skyramp_contract_test_generation, integration: skyramp_integration_test_generation, fuzz: skyramp_fuzz_test_generation, load: skyramp_load_test_generation, e2e: skyramp_e2e_test_generation, ui: skyramp_ui_test_generation. Only generate types in the 'missing' list. For UI/E2E: (1) search repo for existing traces for the target endpoint; (2) if found, use them directly; (3) if not found, run skyramp_start_trace_collection → user interaction → skyramp_stop_trace_collection, then use produced traces. Record each generated test file path for step 4.",
    },
    {
        stepIndex: 4,
        title: "Execute generated tests",
        description: "Before calling skyramp_execute_test, resolve the auth token using only information available to the workflow: (1) if the user provided a token param, use it directly; (2) otherwise, check .skyramp/workspace.yml or other repo config for a documented token value; (3) if no token can be resolved, proceed with empty string '' and rely on skyramp_execute_test to surface 401/403 errors — then report the auth failure to the user and ask them to provide a Bearer token to re-run.",
        toolCall: {
            toolName: "skyramp_execute_test",
            description: "Execute each generated test; resolve token before calling. For each generated test file path returned directly by the generation tools in step 3, invoke this tool with testFile set to that path.",
            inputs: {
                workspacePath: { source: "user", paramKey: "repositoryPath" },
                language: { source: "literal", value: "from workspace" },
                testType: { source: "literal", value: "from generated test / recommendation" },
                testFile: {
                    source: "literal",
                    value: "path to a single generated test file; for each test path returned by generation tools in step 3, call skyramp_execute_test separately with testFile set to that path",
                },
                token: { source: "user", paramKey: "token" },
            },
        },
        conditionalGuidance: "Skip if step 3 generated no tests. Iterate over each generated test file path returned directly from the tools invoked in step 3 and call skyramp_execute_test once per file. Token resolution: (1) user-provided token; (2) token from .skyramp/workspace.yml or repo config; (3) empty string '' — let skyramp_execute_test surface auth errors, then ask the user for a Bearer token to re-run.",
    },
    {
        stepIndex: 5,
        title: "Analyze test health for existing tests (only if step 1 found existing tests for the target endpoint)",
        description: "Run only if step 1 discovered at least one existing test specifically for the target endpoint. Call skyramp_analyze_test_health with the stateFile from step 1. This assesses each existing test for drift and health, then returns instructions for the LLM to assign health scores and actions (UPDATE/REGENERATE/VERIFY). Follow the returned prompt to complete the assessment, then call skyramp_actions in step 7.",
        toolCall: {
            toolName: "skyramp_analyze_test_health",
            description: "Drift and health assessment for existing tests; returns LLM assessment prompt",
            inputs: {
                stateFile: { source: "step", stepIndex: 1, outputKey: "stateFile" },
            },
            outputs: ["stateFile"],
        },
        conditionalGuidance: "Only run when step 1 found existing tests specifically for the target endpoint. If no tests were found for the target endpoint, skip steps 5–7.",
    },
    {
        stepIndex: 6,
        title: "Optional: execute existing tests (only if step 5 ran)",
        description: "Run only if step 5 ran. Optionally execute existing tests using skyramp_execute_test for each test file discovered in the stateFile. Extract test file paths, languages, and types from the stateFile (from step 1), then call skyramp_execute_test once per test with stateFile parameter to write results back. Use token from user or empty string. If you skip this step, proceed directly to step 7.",
        toolCall: {
            toolName: "skyramp_execute_test",
            description: "Optionally run existing tests individually; iterate over tests from stateFile and write results back",
            inputs: {
                workspacePath: { source: "user", paramKey: "repositoryPath" },
                testFile: { source: "literal", value: "path from stateFile existingTests array" },
                language: { source: "literal", value: "language from stateFile existingTests array" },
                testType: { source: "literal", value: "testType from stateFile existingTests array" },
                token: { source: "user", paramKey: "token" },
                stateFile: { source: "step", stepIndex: 1, outputKey: "stateFile" },
            },
            outputs: [],
        },
        conditionalGuidance: "Only run when step 5 was executed. This step is optional — skip if execution is not needed. Read the stateFile from step 1 to get the list of existing tests (existingTests array), then iterate and call skyramp_execute_test once per test with its testFile, language, testType, AND stateFile (from step 1) so execution results are written back for health scoring in step 7.",
    },
    {
        stepIndex: 7,
        title: "Run maintenance actions (only if step 5 ran)",
        description: "Run only if step 5 ran. Call skyramp_actions with the stateFile from step 1 (which now contains execution results if step 6 ran, since skyramp_execute_test writes results back in-place). This applies recommended fixes (UPDATE/REGENERATE/VERIFY) to existing tests and generates tests for new endpoints. Call it immediately after the assessment without waiting for user confirmation.",
        toolCall: {
            toolName: "skyramp_actions",
            description: "Apply recommended test maintenance actions",
            inputs: {
                stateFile: { source: "step", stepIndex: 1, outputKey: "stateFile" },
            },
        },
        conditionalGuidance: "Only run when step 5 was executed. Always use stateFile from step 1 — if step 6 ran, it has updated this file in-place with execution results. The stateFile now contains all the context needed for execution-aware recommendations.",
    },
];
export const TEST_GIVEN_ENDPOINT_COMPREHENSIVELY_COMMAND = {
    id: "test_given_endpoint_comprehensively",
    name: "Test this endpoint comprehensively",
    description: "Comprehensively test a REST API endpoint: analyze changes + discover existing tests + get recommendations in one step, then evaluate missing tests, generate only missing tests, execute them — then (if existing tests were found) run the test health analysis toolset (health assessment → optional batch execute → actions). State files stay in system temp.",
    intent: {
        contextIndicators: [
            "Use when the user names or references a specific REST API endpoint (by path such as /api/products, full URL, or name such as 'products endpoint') and wants a complete multi-step test pipeline for it",
            "Covers the full endpoint testing lifecycle: discover existing tests → evaluate missing coverage → generate missing tests → execute → health analysis → maintenance actions",
            "Only use when the user explicitly signals a full or deep pipeline — words like 'comprehensively', 'thoroughly', 'deep test', 'full test pipeline', or 'all test types'. Do NOT trigger on bare phrases like 'test this endpoint' or 'test the products endpoint' alone — those are ambiguous and may only mean a single smoke test",
            "Do NOT use for broad repo-level requests where no specific endpoint is named — use skyramp_analyze_changes directly instead",
            "Do NOT use for simple single-tool requests such as 'generate a smoke test for this endpoint' — those go directly to the generation tool",
        ],
        purpose: "Deep test a given endpoint: discover existing → evaluate missing → generate missing → execute → (if existing found) health analysis → maintenance actions. Cleanup is handled automatically.",
        workflowSummary: "Analyze Changes → Evaluate missing → Generate missing → Execute generated → [if existing] Test Health → Batch execute → Actions (cleanup is automatic)",
        examples: {
            use: [
                "comprehensively test the products endpoint",
                "thoroughly test /api/v1/orders",
                "deep test the authentication endpoint",
                "run the full test pipeline for /api/users",
            ],
            doNotUse: [
                "test this endpoint → ambiguous, may mean a single smoke test only",
                "generate a smoke test for /api/products → single tool request, call skyramp_smoke_test_generation directly",
                "recommend tests for my PR diff → use skyramp_analyze_changes directly",
                "scan the full repo and run top tests → use full_repo_scan_recommend_generate_and_execute_top_n_tests instead",
            ],
        },
    },
    steps: comprehensivelyTestGivenEndpointSteps,
    inputParams: {
        required: ["repositoryPath"],
        optional: ["endpointURL", "apiSchema", "topN", "token"],
    },
};
