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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
import { Injectable, Logger, OnModuleInit } from "@nestjs/common";
import { PrismaService } from "../prisma/prisma.service";

/**
 * Graph Node Types
 */
type GraphNode = 
    | { type: "guest"; id: string; data: any }
    | { type: "podcast"; id: string; data: any }
    | { type: "host"; id: string; data: any };

type GraphEdge = {
    source: string;
    target: string;
    type: "appeared_on" | "hosted" | "booked" | "knows" | "similar_to";
    weight: number;
    metadata?: Record<string, any>;
};

/**
 * Social Graph Service
 * 
 * Manages the "who knows who" graph for the Verified Guest Network.
 * Enables features like:
 * - "Podcasters who booked X also booked Y"
 * - Guest recommendations based on network proximity
 * - Trust paths between hosts and guests
 * 
 * African Context: Emphasizes community connections and tech hub networks
 */
@Injectable()
export class GraphService implements OnModuleInit {
    private readonly logger = new Logger(GraphService.name);

    // In-memory adjacency list for fast traversal
    // Backed by the graph_edges table for persistence across restarts
    private adjacencyList: Map<string, Map<string, GraphEdge>> = new Map();

    constructor(private readonly prisma: PrismaService) {}

    async onModuleInit() {
        await this.loadEdgesFromDatabase();
    }

    /**
     * Load all graph edges from the database into memory on startup.
     */
    private async loadEdgesFromDatabase(): Promise<void> {
        try {
            const edges = await this.prisma.graphEdge.findMany();
            for (const edge of edges) {
                const sourceId = edge.source;
                const targetId = edge.target;
                const storedEdge: GraphEdge = {
                    source: edge.source,
                    target: edge.target,
                    type: edge.type as GraphEdge["type"],
                    weight: edge.weight,
                    metadata: edge.metadata as Record<string, any>,
                };

                if (!this.adjacencyList.has(sourceId)) {
                    this.adjacencyList.set(sourceId, new Map());
                }
                this.adjacencyList.get(sourceId)!.set(targetId, storedEdge);

                // Restore reverse edges for bidirectional types
                if (edge.type === "knows" || edge.type === "similar_to" || edge.type === "appeared_on") {
                    const reverseEdge = { ...storedEdge, source: edge.target, target: edge.source };
                    if (!this.adjacencyList.has(edge.target)) {
                        this.adjacencyList.set(edge.target, new Map());
                    }
                    this.adjacencyList.get(edge.target)!.set(edge.source, reverseEdge);
                }

                // Restore node data from metadata if available
                if (edge.source.startsWith("guest:") || edge.source.startsWith("podcast:")) {
                    const edges = this.adjacencyList.get(edge.source)!;
                    if (edge.metadata && typeof edge.metadata === "object") {
                        const meta = edge.metadata as Record<string, any>;
                        if (meta.nodeData) {
                            (edges as any).nodeData = meta.nodeData;
                        }
                    }
                }
            }
            this.logger.log(`Loaded ${edges.length} graph edges from database`);
        } catch (error) {
            this.logger.warn("Failed to load graph edges from database, starting with empty graph", error);
        }
    }

    /**
     * Ingest a guest profile into the graph
     */
    async ingestProfile(profileId: string): Promise<void> {
        this.logger.log(`Ingesting profile ${profileId} into graph`);

        const profile = await this.prisma.guestPublicProfile.findUnique({
            where: { id: profileId },
            include: {
                expertiseTags: true,
                bookingHistory: true,
            },
        });

        if (!profile) {
            this.logger.warn(`Profile ${profileId} not found`);
            return;
        }

        // Add guest node
        this.addNode({
            type: "guest",
            id: `guest:${profileId}`,
            data: {
                name: profile.headline,
                country: profile.country,
                expertise: profile.expertiseTags.map((t) => t.name),
                tier: profile.tier,
            },
        });

        // Add appeared_on edges from booking history
        for (const booking of profile.bookingHistory) {
            const podcastNodeId = `podcast:${booking.podcastName}`;
            
            // Add podcast node if not exists
            this.addNode({
                type: "podcast",
                id: podcastNodeId,
                data: { name: booking.podcastName },
            });

            // Add appeared_on edge
            this.addEdge({
                source: `guest:${profileId}`,
                target: podcastNodeId,
                type: "appeared_on",
                weight: 1,
                metadata: {
                    date: booking.appearedAt,
                    topics: booking.topicsDiscussed,
                },
            });
        }

        // Calculate similarity edges to other guests
        await this.calculateSimilarityEdges(profileId, profile.expertiseTags);

        this.logger.log(`Profile ${profileId} ingested successfully`);
    }

    /**
     * Add a node to the graph
     */
    private addNode(node: GraphNode): void {
        if (!this.adjacencyList.has(node.id)) {
            this.adjacencyList.set(node.id, new Map());
        }
        // Store node data in the adjacency list entry
        const edges = this.adjacencyList.get(node.id)!;
        (edges as any).nodeData = node.data;
    }

    /**
     * Add an edge to the graph
     */
    private addEdge(edge: GraphEdge): void {
        // Add forward edge
        if (!this.adjacencyList.has(edge.source)) {
            this.adjacencyList.set(edge.source, new Map());
        }
        this.adjacencyList.get(edge.source)!.set(edge.target, edge);

        // Add reverse edge for undirected relationships (including appeared_on)
        if (edge.type === "knows" || edge.type === "similar_to" || edge.type === "appeared_on") {
            const reverseEdge = { ...edge, source: edge.target, target: edge.source };
            if (!this.adjacencyList.has(edge.target)) {
                this.adjacencyList.set(edge.target, new Map());
            }
            this.adjacencyList.get(edge.target)!.set(edge.source, reverseEdge);
        }

        // Persist to database
        this.persistEdge(edge).catch(err =>
            this.logger.error(`Failed to persist graph edge`, err),
        );
    }

    /**
     * Persist a graph edge to the database.
     */
    private async persistEdge(edge: GraphEdge): Promise<void> {
        try {
            await this.prisma.graphEdge.upsert({
                where: {
                    source_target_type: {
                        source: edge.source,
                        target: edge.target,
                        type: edge.type,
                    },
                },
                create: {
                    source: edge.source,
                    target: edge.target,
                    type: edge.type,
                    weight: edge.weight,
                    metadata: (edge.metadata || {}) as any,
                },
                update: {
                    weight: edge.weight,
                    metadata: (edge.metadata || {}) as any,
                },
            });
        } catch (error) {
            this.logger.error(`Failed to persist edge ${edge.source} -> ${edge.target} (${edge.type})`, error);
        }
    }

    /**
     * Calculate similarity edges based on shared expertise and geography
     */
    private async calculateSimilarityEdges(
        profileId: string,
        expertiseTags: { name: string }[]
    ): Promise<void> {
        const expertiseNames = expertiseTags.map((t) => t.name);
        
        if (expertiseNames.length === 0) return;

        // Find other guests with similar expertise
        const similarGuests = await this.prisma.guestPublicProfile.findMany({
            where: {
                id: { not: profileId },
                isPublic: true,
                expertiseTags: {
                    some: {
                        name: { in: expertiseNames },
                    },
                },
            },
            include: {
                expertiseTags: true,
            },
            take: 20,
        });

        for (const other of similarGuests) {
            const otherExpertise = other.expertiseTags.map((t) => t.name);
            const sharedExpertise = expertiseNames.filter((e) => 
                otherExpertise.includes(e)
            );
            
            if (sharedExpertise.length > 0) {
                const similarityScore = sharedExpertise.length / 
                    Math.max(expertiseNames.length, otherExpertise.length);

                this.addEdge({
                    source: `guest:${profileId}`,
                    target: `guest:${other.id}`,
                    type: "similar_to",
                    weight: similarityScore,
                    metadata: {
                        sharedExpertise,
                        score: similarityScore,
                    },
                });
            }
        }
    }

    /**
     * Get recommendations based on graph proximity
     * "Podcasters who booked X also booked Y"
     */
    async getRecommendations(
        profileId: string,
        limit = 5
    ): Promise<Array<{
        guestId: string;
        reason: string;
        score: number;
    }>> {
        const nodeId = `guest:${profileId}`;
        const scores = new Map<string, number>();
        const reasons = new Map<string, string[]>();

        // Get guests who appeared on the same podcasts
        const appearedOn = this.getNeighbors(nodeId, "appeared_on");
        
        for (const podcastId of appearedOn) {
            const coGuests = this.getNeighbors(podcastId, "appeared_on")
                .filter((g) => g !== nodeId);
            
            for (const coGuest of coGuests) {
                const guestId = coGuest.replace("guest:", "");
                const currentScore = scores.get(guestId) || 0;
                scores.set(guestId, currentScore + 1);
                
                if (!reasons.has(guestId)) {
                    reasons.set(guestId, []);
                }
                const podcastName = this.getNodeData(podcastId)?.name || "a podcast";
                reasons.get(guestId)!.push(`Appeared on ${podcastName}`);
            }
        }

        // Get similar guests
        const similar = this.getNeighbors(nodeId, "similar_to");
        for (const simGuest of similar) {
            const guestId = simGuest.replace("guest:", "");
            const edge = this.getEdge(nodeId, simGuest);
            const currentScore = scores.get(guestId) || 0;
            const weight = edge?.weight || 0.5;
            scores.set(guestId, currentScore + weight);
            
            if (!reasons.has(guestId)) {
                reasons.set(guestId, []);
            }
            const shared = edge?.metadata?.sharedExpertise || ["similar expertise"];
            reasons.get(guestId)!.push(`Shares expertise in ${shared.slice(0, 2).join(", ")}`);
        }

        // Sort by score and return top recommendations
        const sorted = Array.from(scores.entries())
            .sort((a, b) => b[1] - a[1])
            .slice(0, limit);

        return sorted.map(([guestId, score]) => ({
            guestId,
            reason: [...new Set(reasons.get(guestId) || [])].join("; "),
            score,
        }));
    }

    /**
     * Find the shortest path between two guests (trust path)
     */
    async findTrustPath(
        fromProfileId: string,
        toProfileId: string
    ): Promise<string[] | null> {
        const start = `guest:${fromProfileId}`;
        const end = `guest:${toProfileId}`;

        if (!this.adjacencyList.has(start) || !this.adjacencyList.has(end)) {
            return null;
        }

        // BFS for shortest path
        const queue: Array<{ node: string; path: string[] }> = [{ node: start, path: [start] }];
        const visited = new Set<string>();

        while (queue.length > 0) {
            const { node, path } = queue.shift()!;

            if (node === end) {
                return path.map((n) => n.replace("guest:", "").replace("podcast:", ""));
            }

            if (visited.has(node)) continue;
            visited.add(node);

            const neighbors = this.adjacencyList.get(node);
            if (neighbors) {
                for (const [neighbor] of Array.from(neighbors.entries())) {
                    if (!visited.has(neighbor)) {
                        queue.push({ node: neighbor, path: [...path, neighbor] });
                    }
                }
            }
        }

        return null; // No path found
    }

    /**
     * Get network statistics for a profile
     */
    async getNetworkStats(profileId: string): Promise<{
        connections: number;
        reach: number;
        centrality: number;
        communities: string[];
    }> {
        const nodeId = `guest:${profileId}`;
        
        if (!this.adjacencyList.has(nodeId)) {
            return { connections: 0, reach: 0, centrality: 0, communities: [] };
        }

        const directConnections = this.adjacencyList.get(nodeId)!.size;
        
        // Calculate 2-hop reach
        const visited = new Set<string>();
        visited.add(nodeId);
        
        const neighbors = this.getAllNeighbors(nodeId);
        for (const n of Array.from(neighbors)) {
            visited.add(n);
        }
        
        for (const n of Array.from(neighbors)) {
            const secondHop = this.getAllNeighbors(n);
            for (const sh of Array.from(secondHop)) {
                visited.add(sh);
            }
        }

        // Identify communities (tech hubs, countries, expertise areas)
        const communities = this.identifyCommunities(nodeId);

        return {
            connections: directConnections,
            reach: visited.size - 1, // exclude self
            centrality: this.calculateCentrality(nodeId),
            communities,
        };
    }

    /**
     * Get guests in the same network/community
     */
    async getCommunityMembers(
        communityType: "country" | "expertise" | "hub",
        value: string,
        limit = 20
    ): Promise<string[]> {
        const members: string[] = [];

        for (const [nodeId, edges] of Array.from(this.adjacencyList.entries())) {
            if (!nodeId.startsWith("guest:")) continue;
            
            const data = (edges as any).nodeData;
            if (!data) continue;

            if (communityType === "country" && data.country === value) {
                members.push(nodeId.replace("guest:", ""));
            } else if (communityType === "expertise" && data.expertise?.includes(value)) {
                members.push(nodeId.replace("guest:", ""));
            }
        }

        return members.slice(0, limit);
    }

    /**
     * Get neighbors by edge type
     */
    private getNeighbors(nodeId: string, edgeType: string): string[] {
        const edges = this.adjacencyList.get(nodeId);
        if (!edges) return [];

        return Array.from(edges.entries())
            .filter(([, edge]) => edge.type === edgeType)
            .map(([target]) => target);
    }

    /**
     * Get all neighbors regardless of edge type
     */
    private getAllNeighbors(nodeId: string): string[] {
        const edges = this.adjacencyList.get(nodeId);
        if (!edges) return [];
        return Array.from(edges.keys());
    }

    /**
     * Get edge between two nodes
     */
    private getEdge(source: string, target: string): GraphEdge | undefined {
        return this.adjacencyList.get(source)?.get(target);
    }

    /**
     * Get node data
     */
    private getNodeData(nodeId: string): any {
        const edges = this.adjacencyList.get(nodeId);
        if (!edges) return null;
        return (edges as any).nodeData;
    }

    /**
     * Identify communities the node belongs to
     */
    private identifyCommunities(nodeId: string): string[] {
        const data = this.getNodeData(nodeId);
        if (!data) return [];

        const communities: string[] = [];
        
        if (data.country) {
            communities.push(`${data.country} Community`);
        }
        
        if (data.expertise) {
            // Group by top expertise areas
            communities.push(...data.expertise.slice(0, 2).map((e: string) => `${e} Network`));
        }

        return communities;
    }

    /**
     * Calculate a simple centrality score
     */
    private calculateCentrality(nodeId: string): number {
        const direct = this.adjacencyList.get(nodeId)?.size || 0;
        
        // Count unique 2-hop connections
        const twoHop = new Set<string>();
        const neighbors = this.getAllNeighbors(nodeId);
        
        for (const n of neighbors) {
            const secondHop = this.getAllNeighbors(n);
            for (const sh of secondHop) {
                if (sh !== nodeId) {
                    twoHop.add(sh);
                }
            }
        }

        // Simple centrality: combination of direct and 2-hop
        return direct + twoHop.size * 0.5;
    }

    /**
     * Get graph health stats
     */
    getStats(): {
        nodes: number;
        edges: number;
        guests: number;
        podcasts: number;
    } {
        let edges = 0;
        let guests = 0;
        let podcasts = 0;

        for (const [nodeId] of Array.from(this.adjacencyList.entries())) {
            if (nodeId.startsWith("guest:")) guests++;
            if (nodeId.startsWith("podcast:")) podcasts++;
            edges += this.adjacencyList.get(nodeId)!.size;
        }

        return {
            nodes: this.adjacencyList.size,
            edges: edges / 2, // undirected
            guests,
            podcasts,
        };
    }
}