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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
795b72e
 
 
 
 
 
 
 
 
 
 
c2ea5ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
795b72e
 
 
 
 
 
 
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
import React, { useState, useCallback } from "react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";

import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";

import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  AlertCircle,
  CheckCircle,
  Clock,
  Play,
  Eye,
  Zap,
  Shield,
  GitBranch,
  Sparkles,
  Settings,
} from "lucide-react";
import { KnowledgeGraph, PerturbationConfig } from "@/types";
import { useNotification } from "@/context/NotificationContext";
import { api } from "@/lib/api";
import { EnrichResults } from "./EnrichResults";
import { PerturbResults } from "./PerturbResults";
import { PerturbationTestConfig } from "./PerturbationTestConfig";

interface OptionalPipelineSectionProps {
  knowledgeGraph: KnowledgeGraph;
  onStageComplete?: (stage: string) => 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 function OptionalPipelineSection({
  knowledgeGraph,
  onStageComplete,
}: OptionalPipelineSectionProps) {
  const { showNotification } = useNotification();
  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 [selectedStageResults, setSelectedStageResults] = useState<{
    stage: string;
    data: any;
  } | null>(null);

  const [showPerturbConfig, setShowPerturbConfig] = useState(false);

  const getStageStatusColor = (status: StageState["status"]) => {
    switch (status) {
      case "completed":
        return "bg-green-500/10 text-green-700 border-green-200";
      case "running":
        return "bg-blue-500/10 text-blue-700 border-blue-200";
      case "error":
        return "bg-red-500/10 text-red-700 border-red-200";
      default:
        return "bg-gray-500/10 text-gray-700 border-gray-200";
    }
  };

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

      const poll = async () => {
        try {
          const status = await api.tasks.get(taskId);

          setStageStates((prev) => {
            const currentState = prev[stageId] || {
              status: "idle" as const,
              progress: 0,
            };
            return {
              ...prev,
              [stageId]: {
                ...currentState,
                progress: status.progress || currentState.progress,
              },
            };
          });

          if (status.status === "completed" || status.status === "COMPLETED") {
            setStageStates((prev) => ({
              ...prev,
              [stageId]: { status: "completed", progress: 100 },
            }));

            onStageComplete?.(stageId);

            showNotification({
              type: "success",
              title: "Stage Completed",
              message: `${
                PIPELINE_STAGES.find((s) => s.id === stageId)?.name
              } has finished successfully.`,
            });

            return;
          } else if (status.status === "failed" || status.status === "FAILED") {
            setStageStates((prev) => ({
              ...prev,
              [stageId]: {
                status: "error",
                progress: 0,
                error: status.error || "Unknown error",
              },
            }));

            showNotification({
              type: "error",
              title: "Stage Failed",
              message: status.error || "Processing failed",
            });

            return;
          }

          // Continue polling
          attempts++;
          if (attempts < maxAttempts) {
            setTimeout(poll, 5000); // Poll every 5 seconds
          } else {
            // Timeout
            setStageStates((prev) => ({
              ...prev,
              [stageId]: {
                status: "error",
                progress: 0,
                error: "Processing timeout",
              },
            }));
          }
        } catch (error) {
          console.error("Error polling task status:", error);
          // Continue polling on error, might be temporary
          attempts++;
          if (attempts < maxAttempts) {
            setTimeout(poll, 5000);
          }
        }
      };

      // Start polling
      setTimeout(poll, 2000); // First check after 2 seconds
    },
    [onStageComplete, showNotification]
  );

  const runPerturbWithConfig = useCallback(
    async (config: PerturbationConfig) => {
      const stageConfig = PIPELINE_STAGES.find((s) => s.id === "perturb")!;

      setStageStates((prev) => ({
        ...prev,
        perturb: { status: "running", progress: 0 },
      }));

      try {
        const response = await api.knowledgeGraphs.perturb(
          knowledgeGraph.kg_id,
          config
        );

        if (response.task_id) {
          pollTaskStatus("perturb", response.task_id);
          showNotification({
            type: "info",
            title: `${stageConfig.name} Started`,
            message: "Processing has begun with custom configuration.",
          });
        }
      } catch (error) {
        console.error("Error running perturb stage:", error);
        setStageStates((prev) => ({
          ...prev,
          perturb: {
            status: "error",
            progress: 0,
            error: error instanceof Error ? error.message : "Unknown error",
          },
        }));
        showNotification({
          type: "error",
          title: `${stageConfig.name} Failed`,
          message: error instanceof Error ? error.message : "An error occurred",
        });
      }
    },
    [knowledgeGraph.kg_id, showNotification, pollTaskStatus]
  );

  const runStage = useCallback(
    async (stageConfig: PipelineStageConfig) => {
      const { id } = stageConfig;

      // For perturb stage, open the configuration dialog instead
      if (id === "perturb") {
        setShowPerturbConfig(true);
        return;
      }

      setStageStates((prev) => ({
        ...prev,
        [id]: { status: "running", progress: 0 },
      }));

      try {
        // Call the API endpoint based on stage
        let response;

        if (id === "enrich") {
          response = await api.knowledgeGraphs.enrich(knowledgeGraph.kg_id);
        } else if (id === "causal") {
          response = await api.knowledgeGraphs.analyze(knowledgeGraph.kg_id);
        } else {
          throw new Error(`Unknown stage: ${id}`);
        }

        if (response.task_id) {
          // Start polling for task status
          pollTaskStatus(id, response.task_id);

          showNotification({
            type: "info",
            title: `${stageConfig.name} Started`,
            message: "Processing has begun. This may take several minutes.",
          });
        } else {
          // Mark as completed immediately if no task ID
          setStageStates((prev) => ({
            ...prev,
            [id]: { status: "completed", progress: 100 },
          }));

          onStageComplete?.(id);
        }
      } catch (error) {
        console.error(`Error running ${id} stage:`, error);

        setStageStates((prev) => ({
          ...prev,
          [id]: {
            status: "error",
            progress: 0,
            error: error instanceof Error ? error.message : "Unknown error",
          },
        }));

        showNotification({
          type: "error",
          title: `${stageConfig.name} Failed`,
          message: error instanceof Error ? error.message : "An error occurred",
        });
      }
    },
    [knowledgeGraph.kg_id, showNotification, onStageComplete, pollTaskStatus]
  );

  const viewStageResults = useCallback(
    async (stageId: string) => {
      try {
        const results = await api.knowledgeGraphs.getStageResults(
          knowledgeGraph.kg_id,
          stageId
        );

        setSelectedStageResults({
          stage: stageId,
          data: results,
        });
      } catch (error) {
        showNotification({
          type: "error",
          title: "Failed to Load Results",
          message: "Could not retrieve stage results",
        });
      }
    },
    [knowledgeGraph.kg_id, showNotification]
  );

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

  return (
    <>
      <div className="space-y-6">
        {/* Advanced Processing - Unified */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-xl">
              <Zap className="h-6 w-6" />
              Advanced Processing
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-6">
              {/* Description */}
              <div className="text-muted-foreground">
                <p className="text-base">
                  Enhance your knowledge graph with advanced analysis
                  techniques. These optional stages provide deeper insights but
                  are not required for basic graph functionality.
                </p>
              </div>

              {/* Horizontal Stepper */}
              <div className="relative">
                {/* Step Circles - Evenly Distributed */}
                <div className="flex items-center justify-between">
                  {PIPELINE_STAGES.map((stage, index) => {
                    const state = stageStates[stage.id] || {
                      status: "idle" as const,
                      progress: 0,
                    };
                    const StageIcon = stage.icon;

                    return (
                      <div
                        key={stage.id}
                        className="flex flex-col items-center flex-1"
                      >
                        {/* Step Circle */}
                        <div
                          className={`
                            w-12 h-12 rounded-full border-2 flex items-center justify-center transition-all
                            ${
                              state.status === "completed"
                                ? "bg-green-500 border-green-500 text-white"
                                : state.status === "running"
                                ? "bg-blue-500 border-blue-500 text-white animate-pulse"
                                : state.status === "error"
                                ? "bg-red-500 border-red-500 text-white"
                                : "bg-background border-muted-foreground text-muted-foreground"
                            }
                          `}
                        >
                          {state.status === "completed" ? (
                            <CheckCircle className="h-6 w-6" />
                          ) : state.status === "running" ? (
                            <Clock className="h-6 w-6" />
                          ) : state.status === "error" ? (
                            <AlertCircle className="h-6 w-6" />
                          ) : (
                            <StageIcon className="h-6 w-6" />
                          )}
                        </div>

                        {/* Step Number */}
                        <span className="text-xs font-medium mt-1 text-muted-foreground">
                          Step {index + 1}
                        </span>
                      </div>
                    );
                  })}
                </div>

                {/* Connector Lines - Positioned Absolutely */}
                <div className="absolute top-6 left-0 right-0 flex items-center justify-between px-12">
                  {PIPELINE_STAGES.slice(0, -1).map((stage, _index) => {
                    const state = stageStates[stage.id] || {
                      status: "idle" as const,
                      progress: 0,
                    };

                    return (
                      <div
                        key={`connector-${stage.id}`}
                        className="flex-1 mx-8"
                      >
                        <div
                          className={`
                            h-0.5 transition-all
                            ${
                              state.status === "completed"
                                ? "bg-green-500"
                                : "bg-muted-foreground/30"
                            }
                          `}
                        />
                      </div>
                    );
                  })}
                </div>
              </div>

              {/* Stage Labels */}
              <div className="flex items-start justify-between">
                {PIPELINE_STAGES.map((stage, _index) => {
                  const state = stageStates[stage.id] || {
                    status: "idle" as const,
                    progress: 0,
                  };

                  return (
                    <div
                      key={`${stage.id}-label`}
                      className="flex-1 text-center"
                    >
                      <h3 className="font-medium text-sm">{stage.name}</h3>
                      <p className="text-xs text-muted-foreground mt-1 leading-relaxed">
                        {stage.description}
                      </p>
                      <Badge
                        variant="outline"
                        className={`${getStageStatusColor(
                          state.status
                        )} font-medium mt-2`}
                      >
                        {state.status === "idle"
                          ? "Ready"
                          : state.status === "running"
                          ? "Running"
                          : state.status === "completed"
                          ? "Completed"
                          : "Error"}
                      </Badge>
                    </div>
                  );
                })}
              </div>

              {/* Error Display */}
              {Object.values(stageStates).some((s) => s.error) && (
                <div className="p-4 bg-red-50 border border-red-200 rounded-lg">
                  <p className="text-red-700 font-medium">
                    {Object.values(stageStates).find((s) => s.error)?.error}
                  </p>
                </div>
              )}

              {/* Action Buttons - Aligned with Step Circles */}
              <div className="flex items-center justify-between">
                {PIPELINE_STAGES.map((stage) => {
                  const state = stageStates[stage.id] || {
                    status: "idle" as const,
                    progress: 0,
                  };

                  return (
                    <div
                      key={`${stage.id}-action`}
                      className="flex-1 flex justify-center"
                    >
                      {state.status === "idle" && (
                        <Button
                          onClick={() => runStage(stage)}
                          disabled={anyStageRunning}
                          className="gap-2"
                        >
                          {stage.id === "perturb" ? (
                            <>
                              <Settings className="h-4 w-4" />
                              Configure & Run
                            </>
                          ) : (
                            <>
                              <Play className="h-4 w-4" />
                              Run {stage.name}
                            </>
                          )}
                        </Button>
                      )}

                      {state.status === "completed" && (
                        <Button
                          variant="outline"
                          onClick={() => viewStageResults(stage.id)}
                          className="gap-2 bg-green-50 border-green-200 hover:bg-green-100"
                        >
                          <Eye className="h-4 w-4" />
                          View Results
                        </Button>
                      )}

                      {state.status === "error" && (
                        <Button
                          variant="outline"
                          onClick={() => runStage(stage)}
                          disabled={anyStageRunning}
                          className="gap-2"
                        >
                          <Play className="h-4 w-4" />
                          Retry
                        </Button>
                      )}

                      {state.status === "running" && (
                        <Button disabled className="gap-2">
                          <Clock className="h-4 w-4" />
                          Running...
                        </Button>
                      )}
                    </div>
                  );
                })}
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Stage Results Dialog */}
      {selectedStageResults && (
        <Dialog
          open={!!selectedStageResults}
          onOpenChange={() => setSelectedStageResults(null)}
        >
          <DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle>
                {
                  PIPELINE_STAGES.find(
                    (s) => s.id === selectedStageResults.stage
                  )?.name
                }{" "}
                Results
              </DialogTitle>
              <DialogDescription>
                Analysis results for knowledge graph {knowledgeGraph.kg_id}
              </DialogDescription>
            </DialogHeader>
            <div className="mt-4">
              {/* Render appropriate results component based on stage */}
              {selectedStageResults.stage === "enrich" && (
                <EnrichResults
                  data={selectedStageResults.data}
                  knowledgeGraphId={knowledgeGraph.kg_id}
                />
              )}
              {selectedStageResults.stage === "perturb" && (
                <PerturbResults
                  data={selectedStageResults.data}
                  knowledgeGraphId={knowledgeGraph.kg_id}
                />
              )}
              {selectedStageResults.stage === "causal" && (
                <div className="p-8 text-center">
                  <h3 className="text-lg font-semibold mb-2">
                    Causal Analysis Results
                  </h3>
                  <p className="text-muted-foreground mb-4">
                    Rich causal analysis visualization is in development.
                  </p>
                  <pre className="bg-muted p-4 rounded-lg text-sm overflow-auto text-left max-h-96">
                    {JSON.stringify(selectedStageResults.data, null, 2)}
                  </pre>
                </div>
              )}
            </div>
          </DialogContent>
        </Dialog>
      )}

      {/* Perturbation Test Configuration Dialog */}
      <PerturbationTestConfig
        open={showPerturbConfig}
        onOpenChange={setShowPerturbConfig}
        onRun={runPerturbWithConfig}
      />
    </>
  );
}