import path from "node:path";
import { LAB_REPRESENTATIVE_AGENT } from "../../agents/identity.js";
import { appendEvent } from "../observability/index.js";
import { createId, nowIso, readJsonFile, sanitizeText, withFileLock, writeJsonFile } from "../../shared/index.js";
import { ensureTeamRuntime, teamRoot } from "./store.js";
import { sendTeamMessage } from "./mailbox.js";
export function teamMemberRequestsPath(store, runId) {
    return path.join(teamRoot(store, runId), "member-requests.json");
}
export async function listTeamMemberRequests(store, runId) {
    return (await readJsonFile(teamMemberRequestsPath(store, runId))) ?? [];
}
export async function createTeamMemberRequest(store, runId, input) {
    const runtime = await ensureTeamRuntime(store, runId);
    const fromMember = sanitizeText(input.from_member).trim();
    if (!runtime.members.some((member) => member.name === fromMember)) {
        throw new Error(`team member not found: ${fromMember}`);
    }
    const lead = runtime.members.find((member) => member.role === "lead")?.name ?? LAB_REPRESENTATIVE_AGENT;
    const now = nowIso();
    const request = {
        request_id: createId("team_req"),
        run_id: runId,
        from_member: fromMember,
        request_type: input.request_type,
        summary: sanitizeText(input.summary).trim(),
        detail: sanitizeText(input.detail ?? "").trim(),
        suggested_role_id: optionalText(input.suggested_role_id),
        priority: Math.max(1, Math.min(5, Math.floor(input.priority ?? 3))),
        status: "open",
        created_at: now,
        updated_at: now,
    };
    if (!request.summary)
        throw new Error("team member request summary is required");
    const message = await sendTeamMessage(store, runId, {
        from: fromMember,
        to: String(lead),
        kind: "handoff",
        body: `Member request ${request.request_id} (${request.request_type}, p${request.priority}): ${request.summary}${request.detail ? `\n\n${request.detail}` : ""}`,
        metadata: { member_request_id: request.request_id, request_type: request.request_type, suggested_role_id: request.suggested_role_id },
    });
    request.inbox_message_id = message.message_id;
    const file = teamMemberRequestsPath(store, runId);
    await withFileLock(file, async () => {
        const requests = (await readJsonFile(file)) ?? [];
        await writeJsonFile(file, [...requests, request]);
    });
    await appendEvent(store, runId, {
        type: "team_member_request_created",
        actor: fromMember,
        summary: `${request.request_id}: ${request.summary}`,
        metadata: { request, lead, inbox_message_id: message.message_id },
    });
    return request;
}
function optionalText(value) {
    const text = sanitizeText(value ?? "").trim();
    return text || undefined;
}
//# sourceMappingURL=member-request.js.map