import { z } from "zod";
import { randomUUID } from "crypto";
import { WorkspaceConfigManager } from "@skyramp/skyramp";
import { logger } from "../../utils/logger.js";
import { AnalyticsService } from "../../services/AnalyticsService.js";
import { INIT_WORKSPACE_INSTRUCTIONS } from "../../prompts/initialize-workspace/initializeWorkspacePrompt.js";
const TOOL_NAME = "skyramp_init_scan";
// Token store: token -> expiry timestamp (ms)
const scanTokens = new Map();
const TOKEN_TTL_MS = 10 * 60 * 1000; // 10 minutes
export function issueScanToken() {
    const token = randomUUID();
    scanTokens.set(token, Date.now() + TOKEN_TTL_MS);
    return token;
}
export function validateAndConsumeScanToken(token) {
    const expiry = scanTokens.get(token);
    if (!expiry)
        return false;
    scanTokens.delete(token);
    return Date.now() < expiry;
}
const initScanWorkspaceSchema = z.object({
    workspacePath: z.string().describe("Path to the workspace/repository root"),
    force: z
        .boolean()
        .default(false)
        .describe("Set to true to force a re-scan even if .skyramp/workspace.yml already exists. Default is false."),
});
export function registerInitScanWorkspaceTool(server) {
    server.registerTool(TOOL_NAME, {
        description: "PREREQUISITE for skyramp_init_workspace. " +
            "Scans a repository and returns instructions for discovering all services, along with a scanToken. " +
            "Follow the instructions to build the services array, then pass both to skyramp_init_workspace to create the workspace config.",
        inputSchema: initScanWorkspaceSchema.shape,
    }, async (params) => {
        let errorResult;
        const recordParams = { workspacePath: params.workspacePath, force: String(params.force || false) };
        try {
            const manager = new WorkspaceConfigManager(params.workspacePath);
            if ((await manager.exists()) && !params.force) {
                return {
                    content: [
                        {
                            type: "text",
                            text: `Workspace already initialized at ${manager.getConfigPath()}. Set force: true to re-scan and overwrite.`,
                        },
                    ],
                    isError: false,
                };
            }
            const token = issueScanToken();
            return {
                content: [
                    {
                        type: "text",
                        text: `SCAN TOKEN: ${token}\n\nSave this token — you MUST pass it as scanToken when calling skyramp_init_workspace.\n\n${INIT_WORKSPACE_INSTRUCTIONS}`,
                    },
                ],
                isError: false,
            };
        }
        catch (error) {
            const errorMessage = `Failed to start workspace scan: ${error.message || error}`;
            logger.error(errorMessage, error);
            errorResult = {
                content: [{ type: "text", text: errorMessage }],
                isError: true,
            };
            return errorResult;
        }
        finally {
            AnalyticsService.pushMCPToolEvent(TOOL_NAME, errorResult, recordParams);
        }
    });
}
