File size: 27,201 Bytes
c2ea5ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
import React, { useState, useCallback, useEffect } from "react";
import { KnowledgeGraph } from "@/types";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Card, CardContent } from "@/components/ui/card";

import { Button } from "@/components/ui/button";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";

import {
  Sparkles,
  Shield,
  GitBranch,
  Play,
  Clock,
  CheckCircle,
  AlertCircle,
  Trash2,
} from "lucide-react";
import { useNotification } from "@/context/NotificationContext";
import { EnrichResults } from "../traces/EnrichResults";
import { PerturbResults } from "../traces/PerturbResults";
import CausalResults from "../traces/CausalResults";

const API_BASE = "/api";

async function fetchApi<T>(
  endpoint: string,
  options?: RequestInit
): Promise<T> {
  const response = await fetch(`${API_BASE}${endpoint}`, {
    headers: {
      "Content-Type": "application/json",
      ...options?.headers,
    },
    ...options,
  });

  if (!response.ok) {
    throw new Error(`API Error: ${response.statusText}`);
  }

  return response.json();
}

interface AdvancedProcessingViewProps {
  knowledgeGraph: KnowledgeGraph;
  onBack?: () => void;
}

interface StageState {
  status: "idle" | "running" | "completed" | "error";
  progress: number;
  taskId?: string;
  error?: string;
}

interface PipelineStageConfig {
  id: string;
  name: string;
  description: string;
  icon: React.ComponentType<{ className?: string }>;
  apiEndpoint: (kgId: string) => string;
  benefit: string;
}

const PIPELINE_STAGES: PipelineStageConfig[] = [
  {
    id: "enrich",
    name: "Prompt Reconstruction",
    description: "Reconstruct original prompts from conversation patterns",
    icon: Sparkles,
    apiEndpoint: (kgId) => `/knowledge-graphs/${kgId}/enrich`,
    benefit: "Understand conversation context and intent",
  },
  {
    id: "perturb",
    name: "Perturbation Testing",
    description: "Test graph robustness through systematic variations",
    icon: Shield,
    apiEndpoint: (kgId) => `/knowledge-graphs/${kgId}/perturb`,
    benefit: "Validate relationship reliability and stability",
  },
  {
    id: "causal",
    name: "Causal Analysis",
    description: "Analyze causal relationships and dependencies",
    icon: GitBranch,
    apiEndpoint: (kgId) => `/knowledge-graphs/${kgId}/analyze`,
    benefit: "Discover cause-and-effect patterns",
  },
];

export const AdvancedProcessingView: React.FC<AdvancedProcessingViewProps> = ({
  knowledgeGraph: initialKnowledgeGraph,
  onBack: _onBack,
}) => {
  const { showNotification } = useNotification();
  const [knowledgeGraph, setKnowledgeGraph] = useState(initialKnowledgeGraph);
  const [stageStates, setStageStates] = useState<Record<string, StageState>>({
    enrich: {
      status: knowledgeGraph.is_enriched ? "completed" : "idle",
      progress: knowledgeGraph.is_enriched ? 100 : 0,
    },
    perturb: {
      status: knowledgeGraph.is_perturbed ? "completed" : "idle",
      progress: knowledgeGraph.is_perturbed ? 100 : 0,
    },
    causal: {
      status: knowledgeGraph.is_analyzed ? "completed" : "idle",
      progress: knowledgeGraph.is_analyzed ? 100 : 0,
    },
  });

  const [stageResults, setStageResults] = useState<Record<string, any>>({});
  const [loadingResults, setLoadingResults] = useState<Record<string, boolean>>(
    {}
  );
  const [knowledgeGraphData, setKnowledgeGraphData] = useState<any>(null);
  const [progressTimers, setProgressTimers] = useState<
    Record<string, NodeJS.Timeout>
  >({});

  const anyStageRunning = Object.values(stageStates).some(
    (state) => state.status === "running"
  );

  // Estimated durations for each stage (in seconds)
  const STAGE_DURATIONS = {
    enrich: 45, // Prompt Reconstruction typically takes ~45 seconds
    perturb: 90, // Perturbation Testing takes ~90 seconds
    causal: 60, // Causal Analysis takes ~60 seconds
  };

  // Start estimated progress animation
  const startEstimatedProgress = useCallback(
    (stageId: string) => {
      // Clear any existing timer
      if (progressTimers[stageId]) {
        clearInterval(progressTimers[stageId]);
      }

      const duration =
        STAGE_DURATIONS[stageId as keyof typeof STAGE_DURATIONS] || 60;
      const interval = 1000; // Update every second
      const increment = 100 / ((duration * 1000) / interval); // Progress per interval
      let currentProgress = 0;

      const timer = setInterval(() => {
        // Add some randomness to make progress feel more realistic
        const randomVariation = (Math.random() - 0.5) * 0.5; // ±0.25% variation
        currentProgress += increment + randomVariation;

        // Cap at 95% to avoid reaching 100% before completion
        if (currentProgress >= 95) {
          currentProgress = 95;
        }

        // Ensure progress doesn't go backwards
        if (currentProgress < 0) {
          currentProgress = 0;
        }

        setStageStates((prev) => ({
          ...prev,
          [stageId]: {
            ...prev[stageId],
            progress: Math.round(currentProgress),
          } as StageState,
        }));
      }, interval);

      setProgressTimers((prev) => ({
        ...prev,
        [stageId]: timer,
      }));
    },
    [progressTimers]
  );

  // Stop progress animation
  const stopEstimatedProgress = useCallback(
    (stageId: string) => {
      if (progressTimers[stageId]) {
        clearInterval(progressTimers[stageId]);
        setProgressTimers((prev) => {
          const updated = { ...prev };
          delete updated[stageId];
          return updated;
        });
      }
    },
    [progressTimers]
  );

  // Cleanup timers on unmount
  useEffect(() => {
    return () => {
      Object.values(progressTimers).forEach((timer) => clearInterval(timer));
    };
  }, [progressTimers]);

  // Function to refresh knowledge graph data
  const refreshKnowledgeGraph = useCallback(async () => {
    try {
      console.log("🔄 Refreshing knowledge graph status...");
      const response = await fetchApi<any>(
        `/knowledge-graphs/${knowledgeGraph.kg_id}/status`
      );
      console.log("📡 KG Status API Response:", response);
      setKnowledgeGraph((prev) => {
        console.log("📝 Previous KG state:", prev);
        const updated = {
          ...prev,
          is_enriched: response.is_enriched,
          is_perturbed: response.is_perturbed,
          is_analyzed: response.is_analyzed,
          status: response.status,
        };
        console.log("✅ Updated KG state:", updated);
        return updated;
      });
    } catch (error) {
      console.error("❌ Error refreshing knowledge graph status:", error);
    }
  }, [knowledgeGraph.kg_id]);

  const pollTaskStatus = useCallback(
    async (stageId: string, taskId: string) => {
      const maxAttempts = 60; // 5 minutes at 5-second intervals
      let attempts = 0;

      const poll = async (): Promise<void> => {
        try {
          const response = await fetchApi<any>(`/tasks/${taskId}/status`);
          const { status } = response;

          // Note: We're using estimated progress instead of backend progress
          // The progress is managed by the startEstimatedProgress function

          if (status === "COMPLETED") {
            console.log(`🎉 Stage ${stageId} completed! Updating state...`);

            // Stop estimated progress animation and set to 100%
            stopEstimatedProgress(stageId);

            setStageStates((prev) => ({
              ...prev,
              [stageId]: {
                ...prev[stageId],
                status: "completed",
                progress: 100,
              } as StageState,
            }));
            showNotification({
              title: `${
                PIPELINE_STAGES.find((s) => s.id === stageId)?.name
              } completed successfully`,
              message: "The processing stage has been completed successfully.",
              type: "success",
            });
            // Refresh the knowledge graph data to get updated status flags
            console.log(
              `🔄 Calling refreshKnowledgeGraph for stage ${stageId}...`
            );
            await refreshKnowledgeGraph();
            console.log(`✅ Finished refreshing KG for stage ${stageId}`);
            return;
          }

          if (status === "FAILED") {
            // Stop estimated progress animation on failure
            stopEstimatedProgress(stageId);

            setStageStates((prev) => ({
              ...prev,
              [stageId]: {
                ...prev[stageId],
                status: "error",
                error: response.error || "Task failed",
                progress: 0,
              } as StageState,
            }));
            showNotification({
              title: `${
                PIPELINE_STAGES.find((s) => s.id === stageId)?.name
              } failed`,
              message: "The processing stage encountered an error.",
              type: "error",
            });
            return;
          }

          attempts++;
          if (attempts < maxAttempts && status === "RUNNING") {
            setTimeout(poll, 5000);
          }
        } catch (error) {
          console.error("Error polling task status:", error);
          attempts++;
          if (attempts < maxAttempts) {
            setTimeout(poll, 5000);
          }
        }
      };

      poll();
    },
    [showNotification, refreshKnowledgeGraph]
  );

  const runStage = async (stage: PipelineStageConfig) => {
    try {
      setStageStates((prev) => ({
        ...prev,
        [stage.id]: {
          ...prev[stage.id],
          status: "running",
          progress: 0,
          error: undefined,
        },
      }));

      // Start estimated progress animation
      startEstimatedProgress(stage.id);

      const response = await fetchApi<any>(
        stage.apiEndpoint(knowledgeGraph.kg_id),
        {
          method: "POST",
        }
      );
      const { task_id } = response;

      if (task_id) {
        setStageStates((prev) => ({
          ...prev,
          [stage.id]: {
            ...prev[stage.id],
            taskId: task_id,
          } as StageState,
        }));
        pollTaskStatus(stage.id, task_id);
      }
    } catch (error: any) {
      console.error(`Error running ${stage.name}:`, error);

      // Stop progress animation on error
      stopEstimatedProgress(stage.id);

      setStageStates((prev) => ({
        ...prev,
        [stage.id]: {
          ...prev[stage.id],
          status: "error",
          error: error.message,
          progress: 0,
        } as StageState,
      }));
      showNotification({
        title: `Failed to start ${stage.name}`,
        message: "Unable to start the processing stage. Please try again.",
        type: "error",
      });
    }
  };

  const clearStage = async (stage: PipelineStageConfig) => {
    try {
      const response = await fetchApi<any>(
        `/knowledge-graphs/${knowledgeGraph.kg_id}/stage-results/${stage.id}`,
        {
          method: "DELETE",
        }
      );

      const { cleared_stages, new_status } = response;

      // Update knowledge graph status
      setKnowledgeGraph((prev) => ({
        ...prev,
        status: new_status,
        is_enriched:
          new_status === "enriched" ||
          new_status === "perturbed" ||
          new_status === "analyzed",
        is_perturbed: new_status === "perturbed" || new_status === "analyzed",
        is_analyzed: new_status === "analyzed",
      }));

      // Clear results and reset stage states for cleared stages
      const updatedStageStates: Record<string, StageState> = {};
      const updatedStageResults: Record<string, any> = {};

      cleared_stages.forEach((clearedStage: string) => {
        updatedStageStates[clearedStage] = {
          status: "idle",
          progress: 0,
          error: undefined,
        };
        updatedStageResults[clearedStage] = undefined;
      });

      setStageStates((prev) => ({ ...prev, ...updatedStageStates }));
      setStageResults((prev) => {
        const newResults = { ...prev };
        cleared_stages.forEach((clearedStage: string) => {
          delete newResults[clearedStage];
        });
        return newResults;
      });

      showNotification({
        title: `${stage.name} cleared successfully`,
        message: `Cleared ${cleared_stages.join(", ")} stage(s) as requested.`,
        type: "success",
      });
    } catch (error: any) {
      console.error(`Error clearing ${stage.name}:`, error);
      showNotification({
        title: `Failed to clear ${stage.name}`,
        message: "Unable to clear the stage results. Please try again.",
        type: "error",
      });
    }
  };

  const fetchStageResults = useCallback(
    async (stageId: string) => {
      if (loadingResults[stageId]) return;

      setLoadingResults((prev) => ({ ...prev, [stageId]: true }));
      try {
        const response = await fetchApi<any>(
          `/knowledge-graphs/${knowledgeGraph.kg_id}/stage-results/${stageId}`
        );
        setStageResults((prev) => ({ ...prev, [stageId]: response }));
      } catch (error) {
        console.error("Error fetching stage results:", error);
        showNotification({
          title: "Failed to fetch results",
          message: "Unable to retrieve the results for this stage.",
          type: "error",
        });
      } finally {
        setLoadingResults((prev) => ({ ...prev, [stageId]: false }));
      }
    },
    [loadingResults, knowledgeGraph.kg_id, showNotification]
  );

  // Fetch knowledge graph data for component name mapping
  useEffect(() => {
    const fetchKnowledgeGraphData = async () => {
      try {
        const response = await fetchApi<{
          entities: Array<{ id: string; name: string; type: string }>;
          relations: Array<{
            id: string;
            type: string;
            source: string;
            target: string;
          }>;
        }>(`/knowledge-graphs/${knowledgeGraph.kg_id}`);
        setKnowledgeGraphData(response);
      } catch (error) {
        console.error("Error fetching knowledge graph data:", error);
        // Don't show notification for this as it's not critical - causal analysis will still work with IDs
      }
    };

    fetchKnowledgeGraphData();
  }, [knowledgeGraph.kg_id]);

  // Auto-fetch results when stage completes
  useEffect(() => {
    console.log("🔍 Auto-fetch effect triggered. StageStates:", stageStates);
    PIPELINE_STAGES.forEach((stage) => {
      const state = stageStates[stage.id];
      console.log(
        `📊 Stage ${stage.id} state:`,
        state,
        `Results exist:`,
        !!stageResults[stage.id],
        `Loading:`,
        !!loadingResults[stage.id]
      );
      if (
        state?.status === "completed" &&
        !stageResults[stage.id] &&
        !loadingResults[stage.id]
      ) {
        console.log(`🚀 Fetching results for completed stage: ${stage.id}`);
        fetchStageResults(stage.id);
      }
    });
  }, [stageStates, stageResults, loadingResults, fetchStageResults]);

  const renderStageContent = (stage: PipelineStageConfig) => {
    const state = stageStates[stage.id] || {
      status: "idle" as const,
      progress: 0,
    };

    return (
      <div className="space-y-6">
        {/* Progress */}
        {state.status === "running" && (
          <Card>
            <CardContent className="pt-6">
              <div className="space-y-2">
                <div className="flex items-center justify-between">
                  <span className="font-medium">Progress</span>
                  <span className="font-mono">
                    {Math.round(state.progress)}%
                  </span>
                </div>
                <div className="w-full bg-gray-200 rounded-full h-2">
                  <div
                    className="bg-blue-600 h-2 rounded-full transition-all duration-300"
                    style={{ width: `${state.progress}%` }}
                  />
                </div>
              </div>
            </CardContent>
          </Card>
        )}

        {/* Error Display */}
        {state.error && (
          <Card>
            <CardContent className="pt-6">
              <div className="p-4 bg-red-50 border border-red-200 rounded-lg">
                <p className="text-red-700 font-medium">{state.error}</p>
              </div>
            </CardContent>
          </Card>
        )}

        {/* Results Section */}
        {state.status === "completed" && stageResults[stage.id] ? (
          <div className="space-y-6">
            {/* Results Header with Actions */}
            <Card className="border-t-2 border-t-green-500 bg-gradient-to-r from-green-50 to-emerald-50">
              <CardContent className="p-4">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-3">
                    <div className="flex items-center justify-center w-8 h-8 bg-green-100 rounded-full">
                      <CheckCircle className="h-4 w-4 text-green-600" />
                    </div>
                    <div>
                      <h4 className="font-semibold text-green-900">
                        {stage.name} Completed
                      </h4>
                      <p className="text-sm text-green-700">
                        Results are ready to view
                      </p>
                    </div>
                  </div>

                  {/* Action Buttons */}
                  <div className="flex items-center gap-3">
                    <Button
                      onClick={() => runStage(stage)}
                      disabled={anyStageRunning}
                      size="sm"
                      variant="outline"
                      className="gap-2 border-green-200 text-green-700 hover:bg-green-100"
                    >
                      <Play className="h-4 w-4" />
                      Run Again
                    </Button>
                    <Button
                      variant="outline"
                      onClick={() => clearStage(stage)}
                      disabled={anyStageRunning}
                      size="sm"
                      className="gap-2 text-red-600 border-red-200 hover:bg-red-50 hover:border-red-300"
                    >
                      <Trash2 className="h-4 w-4" />
                      Clear
                    </Button>
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* Results Content */}
            <div>
              {stage.id === "enrich" && (
                <EnrichResults
                  data={stageResults[stage.id]}
                  knowledgeGraphId={knowledgeGraph.kg_id}
                  knowledgeGraphData={knowledgeGraphData}
                />
              )}
              {stage.id === "perturb" && (
                <PerturbResults
                  data={stageResults[stage.id]}
                  knowledgeGraphId={knowledgeGraph.kg_id}
                />
              )}
              {stage.id === "causal" && (
                <CausalResults
                  data={stageResults[stage.id]}
                  knowledgeGraphData={knowledgeGraphData}
                />
              )}
            </div>
          </div>
        ) : (
          /* Actions for non-completed stages */
          <Card className="border-dashed border-2 border-gray-200">
            <CardContent className="p-6">
              <div className="text-center space-y-4">
                {state.status === "idle" && (
                  <>
                    <div className="flex items-center justify-center w-12 h-12 bg-blue-50 rounded-full mx-auto">
                      <Play className="h-6 w-6 text-blue-600" />
                    </div>
                    <div>
                      <h4 className="font-medium text-gray-900 mb-1">
                        Ready to Run {stage.name}
                      </h4>
                      <p className="text-sm text-gray-600 mb-4">
                        {stage.description}
                      </p>
                      <Button
                        onClick={() => runStage(stage)}
                        disabled={anyStageRunning}
                        size="lg"
                        className="gap-2"
                      >
                        <Play className="h-5 w-5" />
                        Run {stage.name}
                      </Button>
                    </div>
                  </>
                )}

                {state.status === "completed" && !stageResults[stage.id] && (
                  <>
                    <div className="flex items-center justify-center w-12 h-12 bg-orange-50 rounded-full mx-auto">
                      <AlertCircle className="h-6 w-6 text-orange-600" />
                    </div>
                    <div>
                      <h4 className="font-medium text-gray-900 mb-1">
                        No Results Available
                      </h4>
                      <p className="text-sm text-gray-600 mb-4">
                        The stage completed but no results were found. Try
                        running again.
                      </p>
                      <Button
                        onClick={() => runStage(stage)}
                        disabled={anyStageRunning}
                        size="lg"
                        className="gap-2"
                      >
                        <Play className="h-5 w-5" />
                        Run Again
                      </Button>
                    </div>
                  </>
                )}

                {state.status === "error" && (
                  <>
                    <div className="flex items-center justify-center w-12 h-12 bg-red-50 rounded-full mx-auto">
                      <AlertCircle className="h-6 w-6 text-red-600" />
                    </div>
                    <div>
                      <h4 className="font-medium text-red-900 mb-1">
                        Error Occurred
                      </h4>
                      <p className="text-sm text-red-600 mb-4">
                        {state.error || "An error occurred during processing"}
                      </p>
                      <Button
                        variant="outline"
                        onClick={() => runStage(stage)}
                        disabled={anyStageRunning}
                        size="lg"
                        className="gap-2 border-red-200 text-red-700 hover:bg-red-50"
                      >
                        <Play className="h-5 w-5" />
                        Retry
                      </Button>
                    </div>
                  </>
                )}

                {state.status === "running" && (
                  <>
                    <div className="flex items-center justify-center w-12 h-12 bg-blue-50 rounded-full mx-auto">
                      <Clock className="h-6 w-6 text-blue-600 animate-spin" />
                    </div>
                    <div>
                      <h4 className="font-medium text-blue-900 mb-1">
                        Running {stage.name}
                      </h4>
                      <p className="text-sm text-blue-600 mb-4">
                        Processing in progress... {Math.round(state.progress)}%
                      </p>
                      <Button disabled size="lg" className="gap-2">
                        <Clock className="h-5 w-5" />
                        Running...
                      </Button>
                    </div>
                  </>
                )}

                {loadingResults[stage.id] && (
                  <>
                    <div className="flex items-center justify-center w-12 h-12 bg-purple-50 rounded-full mx-auto">
                      <Clock className="h-6 w-6 text-purple-600 animate-pulse" />
                    </div>
                    <div>
                      <h4 className="font-medium text-purple-900 mb-1">
                        Loading Results
                      </h4>
                      <p className="text-sm text-purple-600 mb-4">
                        Fetching {stage.name.toLowerCase()} results...
                      </p>
                      <Button disabled size="lg" className="gap-2">
                        <Clock className="h-5 w-5" />
                        Loading Results...
                      </Button>
                    </div>
                  </>
                )}
              </div>
            </CardContent>
          </Card>
        )}
      </div>
    );
  };

  return (
    <TooltipProvider>
      <div className="flex flex-col h-screen bg-background">
        <div className="flex-1 overflow-hidden">
          <div className="h-full p-6">
            <Tabs defaultValue="enrich" className="h-full flex flex-col">
              <TabsList className="grid w-full grid-cols-3 mb-6">
                {PIPELINE_STAGES.map((stage) => {
                  const state = stageStates[stage.id];
                  const StageIcon = stage.icon;

                  return (
                    <Tooltip key={stage.id}>
                      <TooltipTrigger asChild>
                        <TabsTrigger
                          value={stage.id}
                          className="flex items-center gap-2 relative"
                        >
                          <StageIcon className="h-4 w-4" />
                          {stage.name}
                          {state?.status === "completed" && (
                            <CheckCircle className="h-3 w-3 text-green-600 absolute -top-1 -right-1" />
                          )}
                          {state?.status === "running" && (
                            <Clock className="h-3 w-3 text-blue-600 absolute -top-1 -right-1 animate-pulse" />
                          )}
                          {state?.status === "error" && (
                            <AlertCircle className="h-3 w-3 text-red-600 absolute -top-1 -right-1" />
                          )}
                        </TabsTrigger>
                      </TooltipTrigger>
                      <TooltipContent>
                        <p>{stage.description}</p>
                      </TooltipContent>
                    </Tooltip>
                  );
                })}
              </TabsList>

              <div className="flex-1 overflow-y-auto">
                {PIPELINE_STAGES.map((stage) => (
                  <TabsContent
                    key={stage.id}
                    value={stage.id}
                    className="h-full mt-0"
                  >
                    <div className="max-w-5xl mx-auto">
                      {renderStageContent(stage)}
                    </div>
                  </TabsContent>
                ))}
              </div>
            </Tabs>
          </div>
        </div>
      </div>
    </TooltipProvider>
  );
};