import { CredentialType } from '@bubblelab/shared-schemas';
import { ServiceBubble } from '../../../types/service-bubble-class.js';
import { GranolaParamsSchema, GranolaResultSchema, } from './granola.schema.js';
const GRANOLA_API_BASE = 'https://public-api.granola.ai';
/**
 * GranolaBubble - Integration with Granola meeting notes API
 *
 * Provides read-only operations for accessing Granola meeting notes:
 * - List notes with pagination and date filtering
 * - Get note details with optional transcript
 *
 * @example
 * ```typescript
 * // List recent notes
 * const result = await new GranolaBubble({
 *   operation: 'list_notes',
 *   page_size: 10,
 * }).action();
 *
 * // Get a specific note with transcript
 * const note = await new GranolaBubble({
 *   operation: 'get_note',
 *   note_id: 'not_1d3tmYTlCICgjy',
 *   include_transcript: true,
 * }).action();
 * ```
 */
export class GranolaBubble extends ServiceBubble {
    static service = 'granola';
    static authType = 'apikey';
    static bubbleName = 'granola';
    static type = 'service';
    static schema = GranolaParamsSchema;
    static resultSchema = GranolaResultSchema;
    static shortDescription = 'Granola meeting notes and transcription integration';
    static longDescription = `
    Granola is an AI meeting notes tool that captures and summarizes meetings.
    This bubble provides read-only access to:
    - List meeting notes with filtering by creation/update dates
    - Paginate through notes using cursor-based pagination
    - Get full note details including summaries, attendees, and calendar events
    - Optionally retrieve meeting transcripts

    Authentication:
    - Uses Bearer token (API key) from Granola Settings > API
    - Requires Business or Enterprise plan for personal keys
    - Enterprise keys access all Team space notes

    Rate Limits:
    - 25 request burst capacity
    - 5 requests/second sustained rate
  `;
    static alias = 'granola-notes';
    constructor(params = {
        operation: 'list_notes',
        page_size: 10,
    }, context) {
        super(params, context);
    }
    chooseCredential() {
        const params = this.params;
        const credentials = params.credentials;
        if (!credentials || typeof credentials !== 'object') {
            return undefined;
        }
        return credentials[CredentialType.GRANOLA_API_KEY];
    }
    async testCredential() {
        const apiKey = this.chooseCredential();
        if (!apiKey) {
            return false;
        }
        // Validate by listing notes with page_size=1
        const response = await fetch(`${GRANOLA_API_BASE}/v1/notes?page_size=1`, {
            method: 'GET',
            headers: {
                Authorization: `Bearer ${apiKey}`,
                'Content-Type': 'application/json',
            },
        });
        if (!response.ok) {
            throw new Error(`Granola API key validation failed: ${response.status}`);
        }
        return true;
    }
    async performAction(context) {
        void context;
        const params = this.params;
        const { operation } = params;
        try {
            switch (operation) {
                case 'list_notes':
                    return (await this.listNotes(params));
                case 'get_note':
                    return (await this.getNote(params));
                default:
                    return {
                        operation: operation,
                        success: false,
                        error: `Unknown operation: ${operation}`,
                    };
            }
        }
        catch (error) {
            return {
                operation: operation,
                success: false,
                error: error instanceof Error ? error.message : String(error),
            };
        }
    }
    // ============================================================================
    // API Methods
    // ============================================================================
    async listNotes(params) {
        const queryParams = new URLSearchParams();
        if (params.created_before)
            queryParams.set('created_before', params.created_before);
        if (params.created_after)
            queryParams.set('created_after', params.created_after);
        if (params.updated_after)
            queryParams.set('updated_after', params.updated_after);
        if (params.cursor)
            queryParams.set('cursor', params.cursor);
        if (params.page_size)
            queryParams.set('page_size', String(params.page_size));
        const url = `${GRANOLA_API_BASE}/v1/notes${queryParams.toString() ? `?${queryParams.toString()}` : ''}`;
        const response = await this.makeGranolaRequest(url);
        if (!response.ok) {
            const errorText = await response.text();
            return {
                operation: 'list_notes',
                success: false,
                error: `Granola API error (${response.status}): ${errorText}`,
            };
        }
        const data = (await response.json());
        return {
            operation: 'list_notes',
            success: true,
            error: '',
            notes: data.notes,
            hasMore: data.hasMore,
            cursor: data.cursor,
        };
    }
    async getNote(params) {
        const queryParams = new URLSearchParams();
        if (params.include_transcript) {
            queryParams.set('include', 'transcript');
        }
        const url = `${GRANOLA_API_BASE}/v1/notes/${params.note_id}${queryParams.toString() ? `?${queryParams.toString()}` : ''}`;
        const response = await this.makeGranolaRequest(url);
        if (!response.ok) {
            const errorText = await response.text();
            return {
                operation: 'get_note',
                success: false,
                error: `Granola API error (${response.status}): ${errorText}`,
            };
        }
        const note = (await response.json());
        return {
            operation: 'get_note',
            success: true,
            error: '',
            note,
        };
    }
    // ============================================================================
    // Helpers
    // ============================================================================
    async makeGranolaRequest(url) {
        const apiKey = this.chooseCredential();
        if (!apiKey) {
            throw new Error('No Granola API key provided');
        }
        return fetch(url, {
            method: 'GET',
            headers: {
                Authorization: `Bearer ${apiKey}`,
                'Content-Type': 'application/json',
            },
        });
    }
}
//# sourceMappingURL=granola.js.map