/**
 * Returns the telemetry entry point based on the runtime context.
 * "testbot" when running as part of the GitHub Action test bot,
 * "mcp" for regular IDE/MCP usage.
 */
import { execFile } from "child_process";
import { promisify } from "util";
import { isTestbotEnabled } from "./featureFlags.js";
import { logger } from "./logger.js";
const execFileAsync = promisify(execFile);
export function getEntryPoint() {
    return isTestbotEnabled() ? "testbot" : "mcp";
}
/**
 * Detects the CI/CD platform from environment variables.
 * Returns undefined when not running in CI.
 */
export function getCIPlatform() {
    if (process.env.GITHUB_ACTIONS === "true")
        return "github";
    if (process.env.GITLAB_CI === "true")
        return "gitlab";
    if (process.env.JENKINS_URL)
        return "jenkins";
    if (process.env.CIRCLECI === "true")
        return "circleci";
    return undefined;
}
/**
 * Parses "owner/repo" out of a git remote URL. Handles both HTTPS
 * (https://github.com/owner/repo.git) and SSH (git@github.com:owner/repo.git)
 * forms, with or without the trailing ".git". Returns undefined if no match.
 */
export function parseRepositoryFromRemoteUrl(remoteUrl) {
    const match = remoteUrl.trim().match(/[:/]([^/]+)\/([^/.]+?)(?:\.git)?$/);
    if (!match)
        return undefined;
    const [, owner, repo] = match;
    return { repository: `${owner}/${repo}`, repositoryOwner: owner };
}
// Memoize the local git lookup per working directory so we shell out at most
// once per cwd for the lifetime of the MCP server process. The value is the
// resolved RepositoryInfo (possibly empty when not a git repo / no remote).
const localRepoInfoCache = new Map();
async function getLocalRepositoryInfo(cwd) {
    const cached = localRepoInfoCache.get(cwd);
    if (cached)
        return cached;
    const lookup = (async () => {
        try {
            const { stdout } = await execFileAsync("git", ["-C", cwd, "remote", "get-url", "origin"], { timeout: 5_000 });
            return parseRepositoryFromRemoteUrl(stdout) ?? {};
        }
        catch (error) {
            // Not a git repo, no "origin" remote, or git not installed — attribute
            // nothing rather than failing the telemetry call.
            logger.debug("Could not resolve local git repository for telemetry", {
                cwd,
                error: error instanceof Error ? error.message : String(error),
            });
            return {};
        }
    })();
    localRepoInfoCache.set(cwd, lookup);
    return lookup;
}
/**
 * Resolves source-repository attribution for telemetry, segmenting usage per
 * customer/repo.
 *
 * - In GitHub Actions (testbot), reads GITHUB_REPOSITORY / GITHUB_REPOSITORY_OWNER
 *   which the MCP subprocess inherits — fast, no shelling out.
 * - In local/IDE usage, derives "owner/repo" from `git remote get-url origin`.
 *   The lookup directory is the caller-supplied `cwd` (a tool's repositoryPath
 *   or workspacePath) when available, since the MCP server's own process.cwd()
 *   is set by the IDE and is not necessarily the user's repo. Falls back to
 *   process.cwd(). Cached per directory so git is invoked at most once each.
 *
 * Returns an empty object when attribution can't be determined (e.g. not a git
 * repo, no origin remote).
 */
export async function getRepositoryInfo(cwd) {
    if (process.env.GITHUB_ACTIONS === "true") {
        const info = {};
        if (process.env.GITHUB_REPOSITORY) {
            info.repository = process.env.GITHUB_REPOSITORY;
        }
        if (process.env.GITHUB_REPOSITORY_OWNER) {
            info.repositoryOwner = process.env.GITHUB_REPOSITORY_OWNER;
        }
        return info;
    }
    return getLocalRepositoryInfo(cwd || process.cwd());
}
