import { requireAuth } from "../security/http-auth.js";
import { interventionRunResumeRegistry } from "../services/intervention-run-resume.js";
const SECRET_SAFE_REASON = "Preview capture is suppressed while the linked browser session is marked secret-safe.";
function buildInterventionResumeMessage(intervention, userNote) {
    const parts = [
        `User completed intervention on browser session ${intervention.browserSessionId}.`,
        `Reason: ${intervention.reason}.`,
        `Instructions: ${intervention.instructions}.`,
    ];
    if (userNote?.trim()) {
        parts.push(`Note: ${userNote.trim()}.`);
    }
    parts.push("Continue from the current browser state where possible.");
    return parts.join(" ");
}
export function registerBrowserCollaborationRoutes(app, config, deps) {
    app.get("/api/browser/sessions", async (request, reply) => {
        const authUser = await requireAuth(request, reply, config.jwtSecret);
        if (!authUser)
            return;
        return { sessions: deps.browserCollaborationService.listSessions(authUser.id) };
    });
    app.get("/api/browser/sessions/:id", async (request, reply) => {
        const authUser = await requireAuth(request, reply, config.jwtSecret);
        if (!authUser)
            return;
        const { id } = request.params;
        const session = deps.browserCollaborationService.getSession(id, authUser.id);
        if (!session)
            return reply.status(404).send({ error: "Browser session not found" });
        const previewSession = session.previewSessionId && deps.previewService
            ? deps.previewService.get(session.previewSessionId)
            : null;
        const interventions = deps.browserCollaborationService
            .listInterventions(authUser.id, "open")
            .filter((item) => item.browserSessionId === session.id);
        return { session, previewSession, interventions };
    });
    app.get("/api/browser/sessions/:id/inspect", async (request, reply) => {
        const authUser = await requireAuth(request, reply, config.jwtSecret);
        if (!authUser)
            return;
        const { id } = request.params;
        const session = deps.browserCollaborationService.getSession(id, authUser.id);
        if (!session)
            return reply.status(404).send({ error: "Browser session not found" });
        if (!session.previewSessionId || !deps.previewService) {
            return reply.status(404).send({ error: "Browser session inspection is not available" });
        }
        if (session.secretSafe) {
            return {
                inspect: null,
                suppressed: true,
                reason: SECRET_SAFE_REASON,
            };
        }
        const query = request.query;
        const inspect = await deps.previewService.inspect(session.previewSessionId, typeof query.selector === "string" ? query.selector : undefined);
        return { inspect };
    });
    app.post("/api/browser/sessions", async (request, reply) => {
        const authUser = await requireAuth(request, reply, config.jwtSecret);
        if (!authUser)
            return;
        const body = (request.body ?? {});
        const session = deps.browserCollaborationService.createSession({
            name: typeof body.name === "string" ? body.name : null,
            workspaceRoot: typeof body.workspaceRoot === "string" ? body.workspaceRoot : null,
            targetUrl: typeof body.targetUrl === "string" ? body.targetUrl : null,
            previewUrl: typeof body.previewUrl === "string" ? body.previewUrl : null,
            previewSessionId: typeof body.previewSessionId === "string" ? body.previewSessionId : null,
            browserId: typeof body.browserId === "string" ? body.browserId : null,
            mode: body.mode === "isolated" ? "isolated" : "shared",
            origin: (body.origin === "managed" || body.origin === "attached" || body.origin === "direct")
                ? body.origin
                : "direct",
            controller: (body.controller === "user" || body.controller === "observer")
                ? body.controller
                : "agent",
            status: (body.status === "running" || body.status === "paused" || body.status === "intervention-required" || body.status === "closed")
                ? body.status
                : "ready",
            secretSafe: Boolean(body.secretSafe),
            storageProfile: body.storageProfile && typeof body.storageProfile === "object"
                ? body.storageProfile
                : null,
            createdBy: authUser.id,
        });
        return { session };
    });
    app.post("/api/browser/sessions/:id/take-control", async (request, reply) => {
        const authUser = await requireAuth(request, reply, config.jwtSecret);
        if (!authUser)
            return;
        const { id } = request.params;
        const session = deps.browserCollaborationService.takeControl(id, authUser.id);
        if (!session)
            return reply.status(404).send({ error: "Browser session not found" });
        return { session };
    });
    app.post("/api/browser/sessions/:id/return-control", async (request, reply) => {
        const authUser = await requireAuth(request, reply, config.jwtSecret);
        if (!authUser)
            return;
        const { id } = request.params;
        const session = deps.browserCollaborationService.returnControl(id, authUser.id);
        if (!session)
            return reply.status(404).send({ error: "Browser session not found" });
        return { session };
    });
    app.post("/api/browser/sessions/:id/pause", async (request, reply) => {
        const authUser = await requireAuth(request, reply, config.jwtSecret);
        if (!authUser)
            return;
        const { id } = request.params;
        const session = deps.browserCollaborationService.pause(id, authUser.id);
        if (!session)
            return reply.status(404).send({ error: "Browser session not found" });
        return { session };
    });
    app.post("/api/browser/sessions/:id/resume", async (request, reply) => {
        const authUser = await requireAuth(request, reply, config.jwtSecret);
        if (!authUser)
            return;
        const { id } = request.params;
        const session = deps.browserCollaborationService.resume(id, authUser.id);
        if (!session)
            return reply.status(404).send({ error: "Browser session not found" });
        return { session };
    });
    app.post("/api/browser/sessions/:id/secret-safe/start", async (request, reply) => {
        const authUser = await requireAuth(request, reply, config.jwtSecret);
        if (!authUser)
            return;
        const { id } = request.params;
        const session = deps.browserCollaborationService.setSecretSafe(id, true, authUser.id);
        if (!session)
            return reply.status(404).send({ error: "Browser session not found" });
        return { session };
    });
    app.post("/api/browser/sessions/:id/secret-safe/stop", async (request, reply) => {
        const authUser = await requireAuth(request, reply, config.jwtSecret);
        if (!authUser)
            return;
        const { id } = request.params;
        const session = deps.browserCollaborationService.setSecretSafe(id, false, authUser.id);
        if (!session)
            return reply.status(404).send({ error: "Browser session not found" });
        return { session };
    });
    app.get("/api/browser/interventions", async (request, reply) => {
        const authUser = await requireAuth(request, reply, config.jwtSecret);
        if (!authUser)
            return;
        const query = request.query;
        const status = query.status === "resolved" || query.status === "cancelled" ? query.status : (query.status === "open" ? "open" : undefined);
        return { interventions: deps.browserCollaborationService.listInterventions(authUser.id, status) };
    });
    app.post("/api/browser/interventions", async (request, reply) => {
        const authUser = await requireAuth(request, reply, config.jwtSecret);
        if (!authUser)
            return;
        const body = (request.body ?? {});
        const browserSessionId = typeof body.browserSessionId === "string" ? body.browserSessionId.trim() : "";
        const reason = typeof body.reason === "string" ? body.reason.trim() : "";
        const instructions = typeof body.instructions === "string" ? body.instructions.trim() : "";
        if (!browserSessionId || !reason || !instructions) {
            return reply.status(400).send({ error: "browserSessionId, reason, and instructions are required" });
        }
        let intervention;
        try {
            intervention = deps.browserCollaborationService.requestIntervention({
                browserSessionId,
                threadId: typeof body.threadId === "string" ? body.threadId : null,
                chatSessionId: typeof body.chatSessionId === "string" ? body.chatSessionId : null,
                kind: (typeof body.kind === "string" ? body.kind : "custom"),
                reason,
                instructions,
                secretSafe: Boolean(body.secretSafe),
                allowUserNote: typeof body.allowUserNote === "boolean" ? body.allowUserNote : true,
                requestedBy: authUser.id,
            });
        }
        catch (error) {
            if (error instanceof Error && error.message.startsWith("Unknown browser session:")) {
                return reply.status(404).send({ error: "Browser session not found" });
            }
            throw error;
        }
        return { intervention };
    });
    app.post("/api/browser/interventions/:id/resolve", async (request, reply) => {
        const authUser = await requireAuth(request, reply, config.jwtSecret);
        if (!authUser)
            return;
        const { id } = request.params;
        const body = (request.body ?? {});
        const userNote = typeof body.userNote === "string" ? body.userNote : null;
        const intervention = deps.browserCollaborationService.resolveIntervention(id, authUser.id, userNote);
        if (!intervention)
            return reply.status(404).send({ error: "Browser intervention not found" });
        const resumeMessage = buildInterventionResumeMessage(intervention, userNote);
        const resume = {
            chat: intervention.chatSessionId
                ? await interventionRunResumeRegistry.resumeChatSession(intervention.chatSessionId, resumeMessage)
                : undefined,
            thread: intervention.threadId
                ? await interventionRunResumeRegistry.resumeThread(intervention.threadId, resumeMessage)
                : undefined,
        };
        return { intervention, resume };
    });
    app.post("/api/browser/interventions/:id/cancel", async (request, reply) => {
        const authUser = await requireAuth(request, reply, config.jwtSecret);
        if (!authUser)
            return;
        const { id } = request.params;
        const intervention = deps.browserCollaborationService.cancelIntervention(id, authUser.id);
        if (!intervention)
            return reply.status(404).send({ error: "Browser intervention not found" });
        return { intervention };
    });
}
//# sourceMappingURL=browser-collaboration.js.map