const require_chunk = require('./chunk-DWy1uDak.cjs');
const require_define = require('./define-BfP4rFlE.cjs');
const require_errors = require('./errors-Bmqdg5Q6.cjs');
const require_api = require('./api-CZD9zwQ-.cjs');
const require_schema = require('./schema-Cv_VNAHz.cjs');
const require_issue_helpers = require('./issue-helpers-DbPTv_qC.cjs');
const require_seer = require('./seer-B63P5CPi.cjs');
const require_fetch_utils = require('./fetch-utils-Cp3P-Ai3.cjs');
const __sentry_core = require_chunk.__toESM(require("@sentry/core"));
const zod = require_chunk.__toESM(require("zod"));

//#region src/tools/analyze-issue-with-seer.ts
var analyze_issue_with_seer_default = require_define.defineTool({
	name: "analyze_issue_with_seer",
	requiredScopes: ["seer"],
	description: [
		"Use Seer to analyze production errors and get detailed root cause analysis with specific code fixes.",
		"",
		"Use this tool when you need:",
		"- Detailed AI-powered root cause analysis",
		"- Specific code fixes and implementation guidance",
		"- Step-by-step troubleshooting for complex issues",
		"- Understanding why an error is happening in production",
		"",
		"What this tool provides:",
		"- Root cause analysis with code-level explanations",
		"- Specific file locations and line numbers where errors occur",
		"- Concrete code fixes you can apply",
		"- Step-by-step implementation guidance",
		"",
		"This tool automatically:",
		"1. Checks if analysis already exists (instant results)",
		"2. Starts new AI analysis if needed (~2-5 minutes)",
		"3. Returns complete fix recommendations",
		"",
		"<examples>",
		"### User: \"What's causing this error? https://my-org.sentry.io/issues/PROJECT-1Z43\"",
		"",
		"```",
		"analyze_issue_with_seer(issueUrl='https://my-org.sentry.io/issues/PROJECT-1Z43')",
		"```",
		"",
		"### User: \"Can you help me understand why this is failing in production?\"",
		"",
		"```",
		"analyze_issue_with_seer(organizationSlug='my-organization', issueId='ERROR-456')",
		"```",
		"</examples>",
		"",
		"<hints>",
		"- Use this tool when you need deeper analysis beyond basic issue details",
		"- If the user provides an issueUrl, extract it and use that parameter alone",
		"- The analysis includes actual code snippets and fixes, not just error descriptions",
		"- Results are cached - subsequent calls return instantly",
		"</hints>"
	].join("\n"),
	inputSchema: {
		organizationSlug: require_schema.ParamOrganizationSlug.optional(),
		regionUrl: require_schema.ParamRegionUrl.optional(),
		issueId: require_schema.ParamIssueShortId.optional(),
		issueUrl: require_schema.ParamIssueUrl.optional(),
		instruction: zod.z.string().describe("Optional custom instruction for the AI analysis").optional()
	},
	annotations: {
		readOnlyHint: false,
		destructiveHint: false,
		openWorldHint: true
	},
	async handler(params, context) {
		const apiService = require_api.apiServiceFromContext(context, { regionUrl: params.regionUrl });
		const { organizationSlug: orgSlug, issueId: parsedIssueId } = require_issue_helpers.parseIssueParams({
			organizationSlug: params.organizationSlug,
			issueId: params.issueId,
			issueUrl: params.issueUrl
		});
		(0, __sentry_core.setTag)("organization.slug", orgSlug);
		let output = `# Seer Analysis for Issue ${parsedIssueId}\n\n`;
		let autofixState = await require_fetch_utils.retryWithBackoff(() => apiService.getAutofixState({
			organizationSlug: orgSlug,
			issueId: parsedIssueId
		}), {
			maxRetries: require_seer.SEER_MAX_RETRIES,
			initialDelay: require_seer.SEER_INITIAL_RETRY_DELAY,
			shouldRetry: (error) => {
				return error instanceof require_errors.ApiServerError || !(error instanceof require_errors.ApiError);
			}
		});
		if (!autofixState.autofix) {
			output += `Starting new analysis...\n\n`;
			const startResult = await apiService.startAutofix({
				organizationSlug: orgSlug,
				issueId: parsedIssueId,
				instruction: params.instruction
			});
			output += `Analysis started with Run ID: ${startResult.run_id}\n\n`;
			await new Promise((resolve) => setTimeout(resolve, 1e3));
			autofixState = await require_fetch_utils.retryWithBackoff(() => apiService.getAutofixState({
				organizationSlug: orgSlug,
				issueId: parsedIssueId
			}), {
				maxRetries: require_seer.SEER_MAX_RETRIES,
				initialDelay: require_seer.SEER_INITIAL_RETRY_DELAY,
				shouldRetry: (error) => {
					return error instanceof require_errors.ApiServerError || !(error instanceof require_errors.ApiError);
				}
			});
		} else {
			output += `Found existing analysis (Run ID: ${autofixState.autofix.run_id})\n\n`;
			const existingStatus = autofixState.autofix.status;
			if (require_seer.isTerminalStatus(existingStatus)) {
				output += `## Analysis ${require_seer.getStatusDisplayName(existingStatus)}\n\n`;
				for (const step of autofixState.autofix.steps) {
					output += require_seer.getOutputForAutofixStep(step);
					output += "\n";
				}
				if (existingStatus !== "COMPLETED") {
					output += `\n**Status**: ${existingStatus}\n`;
					output += require_seer.getHumanInterventionGuidance(existingStatus);
					output += "\n";
				}
				return output;
			}
		}
		const startTime = Date.now();
		let lastStatus = "";
		let consecutiveErrors = 0;
		while (Date.now() - startTime < require_seer.SEER_TIMEOUT) {
			if (!autofixState.autofix) {
				output += `Error: Analysis state lost. Please try again by running:\n`;
				output += `\`\`\`\n`;
				output += params.issueUrl ? `analyze_issue_with_seer(issueUrl="${params.issueUrl}")` : `analyze_issue_with_seer(organizationSlug="${orgSlug}", issueId="${parsedIssueId}")`;
				output += `\n\`\`\`\n`;
				return output;
			}
			const status = autofixState.autofix.status;
			if (require_seer.isTerminalStatus(status)) {
				output += `## Analysis ${require_seer.getStatusDisplayName(status)}\n\n`;
				for (const step of autofixState.autofix.steps) {
					output += require_seer.getOutputForAutofixStep(step);
					output += "\n";
				}
				if (status !== "COMPLETED") {
					output += `\n**Status**: ${status}\n`;
					output += require_seer.getHumanInterventionGuidance(status);
				}
				return output;
			}
			if (status !== lastStatus) {
				const activeStep = autofixState.autofix.steps.find((step) => step.status === "PROCESSING" || step.status === "IN_PROGRESS");
				if (activeStep) output += `Processing: ${activeStep.title}...\n`;
				lastStatus = status;
			}
			await new Promise((resolve) => setTimeout(resolve, require_seer.SEER_POLLING_INTERVAL));
			try {
				autofixState = await require_fetch_utils.retryWithBackoff(() => apiService.getAutofixState({
					organizationSlug: orgSlug,
					issueId: parsedIssueId
				}), {
					maxRetries: require_seer.SEER_MAX_RETRIES,
					initialDelay: require_seer.SEER_INITIAL_RETRY_DELAY,
					shouldRetry: (error) => {
						return error instanceof require_errors.ApiServerError || !(error instanceof require_errors.ApiError);
					}
				});
				consecutiveErrors = 0;
			} catch (error) {
				consecutiveErrors++;
				if (consecutiveErrors >= 3) {
					output += `\n## Error During Analysis\n\n`;
					output += `Unable to retrieve analysis status after multiple attempts.\n`;
					output += `Error: ${error instanceof Error ? error.message : String(error)}\n\n`;
					output += `You can check the status later by running the same command again:\n`;
					output += `\`\`\`\n`;
					output += params.issueUrl ? `analyze_issue_with_seer(issueUrl="${params.issueUrl}")` : `analyze_issue_with_seer(organizationSlug="${orgSlug}", issueId="${parsedIssueId}")`;
					output += `\n\`\`\`\n`;
					return output;
				}
				output += `Temporary error retrieving status (attempt ${consecutiveErrors}/3), retrying...\n`;
			}
		}
		if (autofixState.autofix) {
			output += `**Current Status**: ${require_seer.getStatusDisplayName(autofixState.autofix.status)}\n\n`;
			for (const step of autofixState.autofix.steps) {
				output += require_seer.getOutputForAutofixStep(step);
				output += "\n";
			}
		}
		output += `\n## Analysis Timed Out\n\n`;
		output += `The analysis is taking longer than expected (>${require_seer.SEER_TIMEOUT / 1e3}s).\n\n`;
		output += `\nYou can check the status later by running the same command again:\n`;
		output += `\`\`\`\n`;
		output += params.issueUrl ? `analyze_issue_with_seer(issueUrl="${params.issueUrl}")` : `analyze_issue_with_seer(organizationSlug="${orgSlug}", issueId="${parsedIssueId}")`;
		output += `\n\`\`\`\n`;
		return output;
	}
});

//#endregion
Object.defineProperty(exports, 'analyze_issue_with_seer_default', {
  enumerable: true,
  get: function () {
    return analyze_issue_with_seer_default;
  }
});
//# sourceMappingURL=analyze-issue-with-seer-CI8pvCnf.cjs.map