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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
/**

 * Neo4j Graph Database Adapter

 * 

 * Provides explicit graph storage and querying capabilities using Neo4j.

 * Replaces implicit graph patterns with explicit nodes and relationships.

 */

import neo4j, { Driver, Session, Record as Neo4jRecord, isNode, isRelationship, isPath } from 'neo4j-driver';

export interface GraphNode {
    id: string;
    labels: string[];
    properties: Record<string, any>;
}

export interface GraphRelationship {
    id: string;
    type: string;
    startNodeId: string;
    endNodeId: string;
    properties: Record<string, any>;
}

export interface GraphQueryResult {
    nodes: GraphNode[];
    relationships: GraphRelationship[];
    paths: any[];
    records: Record<string, any>[]; // Added raw records support
}

export interface GraphQueryOptions {
    limit?: number;
    skip?: number;
    where?: Record<string, any>;
    orderBy?: string;
}

export class Neo4jGraphAdapter {
    private driver: Driver | null = null;
    private uri: string;
    private username: string;
    private password: string;
    private database: string;

    constructor() {
        this.uri = process.env.NEO4J_URI || 'bolt://localhost:7687';
        // Support both NEO4J_USER and NEO4J_USERNAME for compatibility
        this.username = process.env.NEO4J_USER || process.env.NEO4J_USERNAME || 'neo4j';
        this.password = process.env.NEO4J_PASSWORD || 'password';
        this.database = process.env.NEO4J_DATABASE || 'neo4j';
    }

    /**

     * Initialize Neo4j connection

     */
    async initialize(): Promise<void> {
        try {
            this.driver = neo4j.driver(
                this.uri,
                neo4j.auth.basic(this.username, this.password),
                {
                    maxConnectionLifetime: 3 * 60 * 60 * 1000, // 3 hours
                    maxConnectionPoolSize: 50,
                    connectionAcquisitionTimeout: 2 * 60 * 1000, // 2 minutes
                }
            );

            // Verify connectivity
            await this.driver.verifyConnectivity();
            console.log('✅ Neo4j connection established');
        } catch (error) {
            console.error('❌ Failed to connect to Neo4j:', error);
            throw error;
        }
    }

    /**

     * Close Neo4j connection

     */
    async close(): Promise<void> {
        if (this.driver) {
            await this.driver.close();
            this.driver = null;
            console.log('✅ Neo4j connection closed');
        }
    }

    /**

     * Get a session for executing queries

     */
    private getSession(): Session {
        if (!this.driver) {
            throw new Error('Neo4j driver not initialized. Call initialize() first.');
        }
        return this.driver.session({ database: this.database });
    }

    /**

     * Create or update a node

     */
    async upsertNode(node: GraphNode): Promise<GraphNode> {
        const session = this.getSession();
        try {
            const labels = node.labels.join(':');
            const props = Object.entries(node.properties)
                .map(([key, value]) => `${key}: $${key}`)
                .join(', ');

            const query = `

                MERGE (n:${labels} {id: $id})

                SET n += {${props}}

                RETURN n

            `;

            const result = await session.run(query, {
                id: node.id,
                ...node.properties
            });

            const record = result.records[0];
            const createdNode = record.get('n');
            
            return {
                id: createdNode.properties.id,
                labels: createdNode.labels,
                properties: createdNode.properties
            };
        } finally {
            await session.close();
        }
    }

    /**

     * Create or update a relationship

     */
    async upsertRelationship(rel: GraphRelationship): Promise<GraphRelationship> {
        const session = this.getSession();
        try {
            const props = Object.entries(rel.properties)
                .map(([key, value]) => `${key}: $${key}`)
                .join(', ');

            const query = `

                MATCH (a {id: $startNodeId})

                MATCH (b {id: $endNodeId})

                MERGE (a)-[r:${rel.type} {id: $id}]->(b)

                SET r += {${props}}

                RETURN r, a.id as startId, b.id as endId

            `;

            const result = await session.run(query, {
                id: rel.id,
                startNodeId: rel.startNodeId,
                endNodeId: rel.endNodeId,
                ...rel.properties
            });

            const record = result.records[0];
            const createdRel = record.get('r');
            
            return {
                id: createdRel.properties.id,
                type: rel.type,
                startNodeId: record.get('startId'),
                endNodeId: record.get('endId'),
                properties: createdRel.properties
            };
        } finally {
            await session.close();
        }
    }

    /**

     * Execute a Cypher query

     */
    async query(cypher: string, parameters?: Record<string, any>): Promise<GraphQueryResult> {
        const session = this.getSession();
        try {
            const result = await session.run(cypher, parameters || {});
            
            const nodes: GraphNode[] = [];
            const relationships: GraphRelationship[] = [];
            const paths: any[] = [];
            const records: Record<string, any>[] = [];

            (result.records || []).forEach((record: Neo4jRecord) => {
                const recordObj: Record<string, any> = {};
                
                record.keys.forEach((key: string) => {
                    const value = record.get(key);
                    recordObj[key] = value;
                    
                    if (isNode(value)) {
                        nodes.push({
                            id: (value.properties.id as string) || value.identity.toString(),
                            labels: value.labels,
                            properties: value.properties
                        });
                    } else if (isRelationship(value)) {
                        relationships.push({
                            id: (value.properties.id as string) || value.identity.toString(),
                            type: value.type,
                            startNodeId: value.start.toString(),
                            endNodeId: value.end.toString(),
                            properties: value.properties
                        });
                    } else if (isPath(value)) {
                        paths.push({
                            start: value.start.properties,
                            end: value.end.properties,
                            length: value.length,
                            segments: value.segments.map((seg: any) => ({
                                start: seg.start.properties,
                                end: seg.end.properties,
                                relationship: seg.relationship.type
                            }))
                        });
                    }
                });
                records.push(recordObj);
            });

            return { nodes, relationships, paths, records };
        } finally {
            await session.close();
        }
    }

    /**

     * Find nodes by label and properties

     */
    async findNodes(
        labels: string[],
        where?: Record<string, any>,
        options?: GraphQueryOptions
    ): Promise<GraphNode[]> {
        const labelStr = labels.join(':');
        let query = `MATCH (n:${labelStr})`;
        
        if (where && Object.keys(where).length > 0) {
            const conditions = Object.entries(where)
                .map(([key, value]) => `n.${key} = $${key}`)
                .join(' AND ');
            query += ` WHERE ${conditions}`;
        }

        if (options?.orderBy) {
            query += ` ORDER BY ${options.orderBy}`;
        }

        if (options?.skip) {
            query += ` SKIP ${options.skip}`;
        }

        if (options?.limit) {
            query += ` LIMIT ${options.limit}`;
        }

        query += ' RETURN n';

        const result = await this.query(query, where);
        return result.nodes;
    }

    /**

     * Find relationships between nodes

     */
    async findRelationships(
        startNodeId: string,
        endNodeId?: string,
        relationshipType?: string
    ): Promise<GraphRelationship[]> {
        let query = `MATCH (a {id: $startNodeId})`;
        
        if (relationshipType) {
            query += `-[r:${relationshipType}]`;
        } else {
            query += `-[r]`;
        }

        if (endNodeId) {
            query += `->(b {id: $endNodeId})`;
        } else {
            query += `->(b)`;
        }

        query += ' RETURN r, a.id as startId, b.id as endId';

        const params: Record<string, any> = { startNodeId };
        if (endNodeId) {
            params.endNodeId = endNodeId;
        }

        const result = await this.query(query, params);
        return result.relationships;
    }

    /**

     * Delete a node and its relationships

     */
    async deleteNode(nodeId: string): Promise<void> {
        const session = this.getSession();
        try {
            await session.run(
                'MATCH (n {id: $id}) DETACH DELETE n',
                { id: nodeId }
            );
        } finally {
            await session.close();
        }
    }

    /**

     * Delete a relationship

     */
    async deleteRelationship(relationshipId: string): Promise<void> {
        const session = this.getSession();
        try {
            await session.run(
                'MATCH ()-[r {id: $id}]-() DELETE r',
                { id: relationshipId }
            );
        } finally {
            await session.close();
        }
    }

    /**

     * Get shortest path between two nodes

     */
    async shortestPath(
        startNodeId: string,
        endNodeId: string,
        relationshipType?: string
    ): Promise<any[]> {
        const relFilter = relationshipType ? `:${relationshipType}` : '';
        const query = `

            MATCH (a {id: $startNodeId}), (b {id: $endNodeId}),

                  path = shortestPath((a)-[${relFilter}*]-(b))

            RETURN path

            LIMIT 1

        `;

        const result = await this.query(query, { startNodeId, endNodeId });
        return result.paths;
    }

    /**

     * Health check

     */
    async healthCheck(): Promise<boolean> {
        try {
            if (!this.driver) {
                return false;
            }
            await this.driver.verifyConnectivity();
            return true;
        } catch {
            return false;
        }
    }

    /**

     * Get statistics

     */
    async getStatistics(): Promise<{
        nodeCount: number;
        relationshipCount: number;
        labelCounts: Record<string, number>;
    }> {
        const session = this.getSession();
        try {
            // Get node count
            const nodeResult = await session.run('MATCH (n) RETURN count(n) as count');
            const nodeCount = nodeResult.records[0].get('count').toNumber();

            // Get relationship count
            const relResult = await session.run('MATCH ()-[r]->() RETURN count(r) as count');
            const relationshipCount = relResult.records[0].get('count').toNumber();

            // Get label counts
            const labelResult = await session.run(`

                CALL db.labels() YIELD label

                CALL apoc.cypher.run('MATCH (n:' + label + ') RETURN count(n) as count', {}) YIELD value

                RETURN label, value.count as count

            `);

            const labelCounts: Record<string, number> = {};
            labelResult.records.forEach(record => {
                labelCounts[record.get('label')] = record.get('count').toNumber();
            });

            return { nodeCount, relationshipCount, labelCounts };
        } catch (error) {
            // Fallback if APOC is not available
            const labelResult = await session.run(`

                MATCH (n)

                RETURN DISTINCT labels(n) as labels, count(n) as count

            `);
            
            const labelCounts: Record<string, number> = {};
            let nodeCount = 0;
            const relationshipCount = 0;

            (labelResult.records || []).forEach(record => {
                const labels = record.get('labels');
                const count = record.get('count').toNumber();
                labels.forEach((label: string) => {
                    labelCounts[label] = (labelCounts[label] || 0) + count;
                    nodeCount += count;
                });
            });

            return {
                nodeCount: nodeCount,
                relationshipCount: relationshipCount,
                labelCounts
            };
        } finally {
            await session.close();
        }
    }
}

// Singleton instance
let neo4jAdapterInstance: Neo4jGraphAdapter | null = null;

export function getNeo4jGraphAdapter(): Neo4jGraphAdapter {
    if (!neo4jAdapterInstance) {
        neo4jAdapterInstance = new Neo4jGraphAdapter();
    }
    return neo4jAdapterInstance;
}