import bodyParser from "body-parser";
import { SnapshotRestoreError, } from "./ai-service/recording/snapshot-manager.js";
import { getErrorMeta } from "./util/logger.js";
export function registerSnapshotRoutes(server, options) {
    const { getIsInitialized, appRootDir, snapshotManager, socketManager: _socketManager, logger, getAvailableIntegrationIds, isSessionManagementEnabled, } = options;
    if (!isSessionManagementEnabled) {
        return;
    }
    // POST /sb-snapshots/upload - accepts tar.gz, extracts, returns uploadId/details
    server.middlewares.use("/sb-snapshots/upload", (req, res, next) => {
        void (async () => {
            if (!getIsInitialized()) {
                return next();
            }
            if (req.method !== "POST" && req.method !== "OPTIONS") {
                res.statusCode = 405;
                res.end("Method not allowed");
                return;
            }
            res.setHeader("Access-Control-Allow-Origin", "*");
            res.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
            res.setHeader("Access-Control-Allow-Headers", "Content-Type, Content-Length");
            if (req.method === "OPTIONS") {
                res.statusCode = 204;
                res.end();
                return;
            }
            try {
                const chunks = [];
                for await (const chunk of req) {
                    chunks.push(Buffer.from(chunk));
                }
                const archiveBuffer = Buffer.concat(chunks);
                if (archiveBuffer.length === 0) {
                    res.statusCode = 400;
                    res.setHeader("Content-Type", "application/json");
                    res.end(JSON.stringify({ error: "Empty request body" }));
                    return;
                }
                if (!snapshotManager) {
                    res.statusCode = 503;
                    res.setHeader("Content-Type", "application/json");
                    res.end(JSON.stringify({
                        error: "Snapshot manager not initialized",
                    }));
                    return;
                }
                const result = await snapshotManager.upload(archiveBuffer);
                const details = await snapshotManager.getDetails();
                res.setHeader("Content-Type", "application/json");
                res.end(JSON.stringify({
                    success: true,
                    hasUpload: true,
                    uploadId: result.uploadId,
                    extractedDir: result.extractedDir,
                    uploadedAt: result.uploadedAt.toISOString(),
                    details,
                }));
            }
            catch (error) {
                logger.error("Error uploading snapshot", getErrorMeta(error));
                if (!res.headersSent) {
                    res.statusCode = 500;
                    res.setHeader("Content-Type", "application/json");
                    res.end(JSON.stringify({
                        error: error instanceof Error
                            ? error.message
                            : "Failed to upload snapshot",
                    }));
                }
            }
        })();
    });
    // GET /sb-snapshots/info - returns current upload state or hasUpload: false
    server.middlewares.use("/sb-snapshots/info", (req, res, next) => {
        void (async () => {
            if (!getIsInitialized()) {
                return next();
            }
            if (req.method !== "GET" && req.method !== "OPTIONS") {
                res.statusCode = 405;
                res.end("Method not allowed");
                return;
            }
            res.setHeader("Access-Control-Allow-Origin", "*");
            res.setHeader("Access-Control-Allow-Methods", "GET, OPTIONS");
            res.setHeader("Access-Control-Allow-Headers", "Content-Type");
            if (req.method === "OPTIONS") {
                res.statusCode = 204;
                res.end();
                return;
            }
            if (!snapshotManager) {
                res.statusCode = 503;
                res.setHeader("Content-Type", "application/json");
                res.end(JSON.stringify({
                    error: "Snapshot manager not initialized",
                }));
                return;
            }
            const uploadState = await snapshotManager.getUpload();
            const details = uploadState ? await snapshotManager.getDetails() : null;
            res.setHeader("Content-Type", "application/json");
            if (uploadState) {
                res.end(JSON.stringify({
                    hasUpload: true,
                    uploadId: uploadState.uploadId,
                    extractedDir: uploadState.extractedDir,
                    uploadedAt: uploadState.uploadedAt.toISOString(),
                    details,
                }));
            }
            else {
                res.end(JSON.stringify({ hasUpload: false }));
            }
        })();
    });
    // POST /sb-snapshots/analyze - body { uploadId, sessionId? }, return snapshot metadata
    server.middlewares.use("/sb-snapshots/analyze", bodyParser.json({ strict: true }));
    server.middlewares.use("/sb-snapshots/analyze", (req, res, next) => {
        void (async () => {
            if (!getIsInitialized()) {
                return next();
            }
            if (req.method !== "POST" && req.method !== "OPTIONS") {
                res.statusCode = 405;
                res.end("Method not allowed");
                return;
            }
            res.setHeader("Access-Control-Allow-Origin", "*");
            res.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
            res.setHeader("Access-Control-Allow-Headers", "Content-Type");
            if (req.method === "OPTIONS") {
                res.statusCode = 204;
                res.end();
                return;
            }
            if (!snapshotManager) {
                res.statusCode = 503;
                res.setHeader("Content-Type", "application/json");
                res.end(JSON.stringify({
                    error: "Snapshot manager not initialized",
                }));
                return;
            }
            const body = req.body;
            if (!body?.uploadId || typeof body.uploadId !== "string") {
                res.statusCode = 400;
                res.setHeader("Content-Type", "application/json");
                res.end(JSON.stringify({
                    error: "Missing required field: uploadId",
                }));
                return;
            }
            const { uploadId, sessionId } = body;
            try {
                const meta = await snapshotManager.analyze(uploadId, sessionId ?? undefined);
                res.setHeader("Content-Type", "application/json");
                res.end(JSON.stringify({ success: true, meta }));
            }
            catch (error) {
                if (error instanceof SnapshotRestoreError) {
                    res.statusCode = 400;
                    res.setHeader("Content-Type", "application/json");
                    res.end(JSON.stringify({ error: error.message }));
                    return;
                }
                logger.error("Error analyzing snapshot", getErrorMeta(error));
                if (!res.headersSent) {
                    res.statusCode = 500;
                    res.setHeader("Content-Type", "application/json");
                    res.end(JSON.stringify({
                        error: error instanceof Error
                            ? error.message
                            : "Failed to analyze snapshot",
                    }));
                }
            }
        })();
    });
    // POST /sb-snapshots/restore - body { uploadId, sessionId? }, restore then sync
    server.middlewares.use("/sb-snapshots/restore", bodyParser.json({ strict: true }));
    server.middlewares.use("/sb-snapshots/restore", (req, res, next) => {
        void (async () => {
            if (!getIsInitialized()) {
                return next();
            }
            if (req.method !== "POST" && req.method !== "OPTIONS") {
                res.statusCode = 405;
                res.end("Method not allowed");
                return;
            }
            res.setHeader("Access-Control-Allow-Origin", "*");
            res.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
            res.setHeader("Access-Control-Allow-Headers", "Content-Type");
            if (req.method === "OPTIONS") {
                res.statusCode = 204;
                res.end();
                return;
            }
            if (!snapshotManager) {
                res.statusCode = 503;
                res.setHeader("Content-Type", "application/json");
                res.end(JSON.stringify({
                    error: "Snapshot manager not initialized",
                }));
                return;
            }
            const body = req.body;
            if (!body?.uploadId || typeof body.uploadId !== "string") {
                res.statusCode = 400;
                res.setHeader("Content-Type", "application/json");
                res.end(JSON.stringify({
                    error: "Missing required field: uploadId",
                }));
                return;
            }
            const { uploadId, sessionId, sanitizeIntegrations } = body;
            try {
                const availableIntegrationIds = await getAvailableIntegrationIds?.();
                const { sourceDir } = await snapshotManager.prepareRestoreSource(uploadId, sessionId, appRootDir, availableIntegrationIds, sanitizeIntegrations);
                await snapshotManager.createPendingRestore(appRootDir, uploadId, sourceDir);
                res.setHeader("Content-Type", "application/json");
                res.end(JSON.stringify({ success: true }));
            }
            catch (error) {
                if (error instanceof SnapshotRestoreError) {
                    res.statusCode = 400;
                    res.setHeader("Content-Type", "application/json");
                    res.end(JSON.stringify({ error: error.message }));
                    return;
                }
                logger.error("Error restoring snapshot", getErrorMeta(error));
                if (!res.headersSent) {
                    res.statusCode = 500;
                    res.setHeader("Content-Type", "application/json");
                    res.end(JSON.stringify({
                        error: error instanceof Error
                            ? error.message
                            : "Failed to restore snapshot",
                    }));
                }
            }
        })();
    });
}
//# sourceMappingURL=snapshot-routes.js.map