/**
 * Event Ingest API — meeting capture adapter
 *
 * POST /api/repos/:repo/events/ingest
 * GET  /api/repos/:repo/events/ingest/:entityId/extraction
 *
 * Thin route that accepts desktop or external meeting payloads and delegates
 * to the source-agnostic EventProcessor.
 */
import * as access from '../../services/access-control.js';
import { EventProcessor } from '../../services/event-processor.js';
// ── Adapter: transform event payload → common MeetingPayload ──────────
function toMeetingPayload(body) {
    return {
        sourceId: body.meetingId,
        source: body.source || 'desktop-client',
        title: body.title,
        startedAt: body.startedAt,
        endedAt: body.endedAt,
        durationMinutes: body.durationMinutes,
        participants: body.participants.map(p => ({
            name: p.name,
            email: p.email,
            isSelf: p.isSelf,
        })),
        transcript: body.transcript.map(s => ({
            speaker: s.speaker,
            text: s.text,
            timestamp: s.timestamp,
            isFinal: s.isFinal,
            channel: s.channel,
        })),
        memo: body.memo || undefined,
        platform: body.platform,
        meetingUrl: body.meetingUrl,
    };
}
function reqGitUser(req) {
    const user = req.user;
    if (!user)
        return undefined;
    // Use email as id (see graph-api.ts reqGitUser for rationale).
    return { id: user.email, name: user.displayName, email: user.email };
}
// ── Route Registration ────────────────────────────────────────────────
export async function registerEventIngestRoutes(fastify, workspaceManager, authService, wsHub, yjsManager) {
    const processor = new EventProcessor(workspaceManager, wsHub, yjsManager);
    const handlePost = async (req, reply) => {
        const { repo } = req.params;
        const body = req.body;
        // Access gate: ingest writes to disk + invokes LLM, both as the
        // calling user. Without this, any authenticated user could inject
        // meetings into a folder they don't have access to.
        const user = req.user;
        if (!access.canWriteRepo(user, repo, workspaceManager, authService)) {
            return reply.status(404).send({ error: `Folder "${repo}" not found` });
        }
        try {
            workspaceManager.getGraph(repo);
        }
        catch (err) {
            return reply.status(404).send({ error: `Folder "${repo}" not found` });
        }
        // Transcript required unless updating an existing entity (desktop app flow)
        if (!body.existingEntityId && (!body.transcript || body.transcript.length === 0)) {
            return reply.status(400).send({ error: 'transcript is required and must not be empty' });
        }
        try {
            const payload = toMeetingPayload(body);
            if (body.existingEntityId) {
                // Meeting capture UI: entity already created by the web app.
                // Update it with transcript and run LLM processing.
                const result = await processor.processExisting(payload, repo, body.existingEntityId, reqGitUser(req));
                return reply.status(200).send({
                    entityId: result.entityId,
                    url: result.url,
                    linkedPeople: result.attendeeLinks,
                    extractionPending: result.extractionPending,
                });
            }
            const result = await processor.process(payload, repo, reqGitUser(req));
            return reply.status(201).send({
                entityId: result.entityId,
                url: result.url,
                linkedPeople: result.attendeeLinks,
                extractionPending: result.extractionPending,
            });
        }
        catch (err) {
            if (err.message?.includes('already exists')) {
                return reply.status(409).send({ error: err.message });
            }
            return reply.status(400).send({ error: err.message });
        }
    };
    const handleGetExtraction = async (req, reply) => {
        const { repo, entityId } = req.params;
        const user = req.user;
        if (!access.hasRepoAccess(user, repo, workspaceManager, authService)) {
            return reply.status(404).send({ error: `Folder "${repo}" not found` });
        }
        try {
            const graph = workspaceManager.getGraph(repo);
            const entity = graph.get('event', entityId);
            const d = entity.data;
            const content = entity.document?.content || '';
            const ready = d?.processing !== true;
            return reply.send({
                entityId,
                ready,
                summary: ready ? content.split('\n---\n')[0]?.trim() : null,
                actionItems: Array.isArray(d?.action_items) ? d.action_items : [],
                decisions: [],
            });
        }
        catch (err) {
            return reply.status(404).send({ error: err.message });
        }
    };
    // POST — ingest an event (currently only meeting recordings).
    fastify.post('/api/repos/:repo/events/ingest', handlePost);
    // GET — poll for summary completion.
    fastify.get('/api/repos/:repo/events/ingest/:entityId/extraction', handleGetExtraction);
}
//# sourceMappingURL=event-ingest-api.js.map