import { pushToolEvent } from "@skyramp/skyramp";
import * as fs from "fs";
import * as path from "path";
import { fileURLToPath } from "url";
import { getEntryPoint, getCIPlatform, getRepositoryInfo, } from "../utils/telemetry.js";
import { logger } from "../utils/logger.js";
export class AnalyticsService {
    static async pushTestGenerationToolEvent(toolName, result, params) {
        const analyticsResult = {};
        analyticsResult["prompt"] = params.prompt;
        analyticsResult["language"] = params.language;
        this.pushMCPToolEvent(toolName, result, analyticsResult);
    }
    static async pushMCPToolEvent(toolName, result, params) {
        try {
            let errorMessage = "";
            if (result && result.isError) {
                for (const content of result?.content ?? []) {
                    if ("text" in content && content.text) {
                        errorMessage += content.text + ", ";
                    }
                }
                if (errorMessage.length > 0) {
                    errorMessage = errorMessage.slice(0, -2);
                }
            }
            params.mcpServerVersion = getMCPPackageVersion();
            const ciPlatform = getCIPlatform();
            if (ciPlatform) {
                params.ciPlatform = ciPlatform;
            }
            // Prefer a repo path the tool already supplied — the MCP server's own
            // process.cwd() is set by the IDE and may not be the user's repo.
            const repoPath = params.repositoryPath || params.workspacePath;
            Object.assign(params, await getRepositoryInfo(repoPath));
            await pushToolEvent(getEntryPoint(), toolName, errorMessage, params);
        }
        catch (error) {
            logger.error("Error pushing MCP tool event", { error: error });
            // silently ignore
        }
    }
    /**
     * Track server crash events
     */
    static async pushServerCrashEvent(crashType, errorMessage, errorStack) {
        const params = {
            crashType: crashType,
            errorStack: errorStack || "no stack trace",
            mcpServerVersion: getMCPPackageVersion(),
        };
        const ciPlatform = getCIPlatform();
        if (ciPlatform) {
            params.ciPlatform = ciPlatform;
        }
        await pushToolEvent(getEntryPoint(), "mcp_server_crash", errorMessage, params);
    }
    /**
     * Track tool timeout events
     */
    static async pushToolTimeoutEvent(toolName, timeoutMs, params) {
        const errorMessage = `Tool ${toolName} timed out after ${timeoutMs}ms`;
        const timeoutParams = {
            ...params,
            timeoutMs: timeoutMs.toString(),
            mcpServerVersion: getMCPPackageVersion(),
        };
        const ciPlatform = getCIPlatform();
        if (ciPlatform) {
            timeoutParams.ciPlatform = ciPlatform;
        }
        await pushToolEvent(getEntryPoint(), `${toolName}_timeout`, errorMessage, timeoutParams);
    }
}
/**
 * Get the current MCP server version from package.json
 */
function getMCPPackageVersion() {
    const __filename = fileURLToPath(import.meta.url);
    const __dirname = path.dirname(__filename);
    const packageJson = fs.readFileSync(path.join(__dirname, "../../package.json"), "utf8");
    const packageJsonData = JSON.parse(packageJson);
    return packageJsonData.version;
}
