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
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
"use client";

import { ObjectJsonSchema7 } from "app-types/util";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
  DialogFooter,
  DialogClose,
} from "ui/dialog";
import { Button } from "ui/button";
import { Label } from "ui/label";
import { Textarea } from "ui/textarea";

import { Tabs, TabsContent, TabsList, TabsTrigger } from "ui/tabs";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "ui/card";
import {
  PlusIcon,
  TrashIcon,
  WandSparklesIcon,
  CodeIcon,
  FileTextIcon,
  PencilIcon,
  VariableIcon,
} from "lucide-react";
import {
  EditJsonSchemaFieldPopup,
  Feild,
} from "../edit-json-schema-field-popup";
import { useState, useCallback, useMemo, useEffect } from "react";
import { toast } from "sonner";
import { generateObjectAction } from "@/app/api/chat/actions";
import { appStore } from "@/app/store";
import { SelectModel } from "../select-model";
import { notify } from "lib/notify";
import { useTranslations } from "next-intl";
import { JSONSchema7 } from "json-schema";
import { defaultObjectJsonSchema } from "lib/ai/workflow/shared.workflow";
import { errorToString, validateSchema } from "lib/utils";
import { safe } from "ts-safe";
import { jsonSchemaToZod } from "lib/json-schema-to-zod";

type SchemaEditMode = "simple" | "advanced";

interface OutputSchemaEditorProps {
  children: React.ReactNode;
  onChange: (schema: ObjectJsonSchema7) => void;
  schema?: ObjectJsonSchema7;
  open?: boolean;
  onOpenChange?: (open: boolean) => void;
}

const isObjectJsonSchema7 = (schema: any): schema is ObjectJsonSchema7 => {
  if (!schema) return false;
  return schema.type === "object";
};

const placeholderJsonSchema = `{
  "type": "object",
  "properties": {
    "result": {
      "type": "string",
      "description": "The result of the operation"
    },
    "status": {
      "type": "number",
      "description": "HTTP status code"
    },
    "data": {
      "type": "object",
      "properties": {
        "items": {
          "type": "array",
          "items": {"type": "string"}
        },
        "count": {"type": "number"}
      }
    }
  },
  "required": ["result", "status"]
}`;

export function OutputSchemaEditor({
  children,
  onChange,
  schema,
  open,
  onOpenChange,
}: OutputSchemaEditorProps) {
  const t = useTranslations();
  const [mode, setMode] = useState<SchemaEditMode>("simple");
  const [localSchema, setLocalSchema] = useState<ObjectJsonSchema7>(
    structuredClone(defaultObjectJsonSchema),
  );
  const [advancedJson, setAdvancedJson] = useState("");

  const fields = useMemo(() => {
    const properties = localSchema.properties || {};
    return Object.entries(properties).map(([key, value]) => ({
      key,
      type: getFieldType(value),
      required: localSchema.required?.includes(key) || false,
      description: (value as any).description,
      enum: (value as any).enum,
      defaultValue: (value as any).default,
    }));
  }, [localSchema]);

  const handleSave = () => {
    const isDirectTab = mode === "advanced";
    if (isDirectTab) {
      const isValid = validate(advancedJson);
      if (!isValid) return;
    }
    onChange(isDirectTab ? JSON.parse(advancedJson) : localSchema);
    onOpenChange?.(false);
  };

  const validate = useCallback((json: string): boolean => {
    return safe(() => JSON.parse(json) as ObjectJsonSchema7)
      .map((s) => {
        if (!isObjectJsonSchema7(s))
          throw new Error("Root schema must be an object");
        validateSchema("answer", s);
        jsonSchemaToZod(s); // for checking if the schema is valid
        return true;
      })
      .ifFail((e) => {
        toast.error(errorToString(e));
        return false;
      })
      .orElse(false);
  }, []);

  const handleGenerateWithAI = useCallback(async () => {
    let model = appStore.getState().chatModel;
    const result = await notify.prompt({
      title: t("Workflow.generateSchemaWithAI"),
      description: (
        <div className="flex items-center gap-2">
          <p className="mr-auto whitespace-pre-wrap">
            {t("Workflow.describeOutputDataRequest", {
              eg: '{"name": "John", "age": 30}',
            })}
          </p>
          <SelectModel
            onSelect={(m) => {
              model = m;
            }}
          />
        </div>
      ),
    });
    if (!result) return;
    toast.promise(
      generateObjectAction({
        model,
        prompt: {
          system: `You are an expert JSON Schema Draft 7 generator for workflow automation systems.

Your task is to generate a comprehensive JSON Schema based on the user's input. Handle two types of input:

1. **Example JSON Data**: If the user provides JSON data, analyze it and generate a schema that validates that structure.

2. **Natural Language Description**: If the user describes what they want (not JSON), follow these steps:
   - First, identify the main data class/entity from their description
   - Think about what properties this entity should have
   - Consider realistic data types and structure for that domain
   - Generate an appropriate JSON Schema for that concept

Key Guidelines:
- The root schema type is ALWAYS "object" (workflow nodes output object data by default)
- Include meaningful "description" fields for each property
- Mark essential fields as "required" based on context
- Use appropriate JSON Schema data types: string, number, boolean, array, object
- For arrays, create proper "items" schemas
- For nested objects, create proper "properties" definitions
- Focus on creating schemas that enable rich data flow between workflow nodes

Examples:

JSON Data Input: {"name": "John", "age": 25}
Output: {
  "type": "object",
  "properties": {
    "name": {"type": "string", "description": "Person's name"},
    "age": {"type": "number", "description": "Person's age"}
  },
  "required": ["name", "age"]
}

Natural Language Input: "User profile data"
Output: {
  "type": "object",
  "properties": {
    "id": {"type": "string", "description": "Unique user identifier"},
    "name": {"type": "string", "description": "User's full name"},
    "email": {"type": "string", "description": "User's email address"},
    "createdAt": {"type": "string", "description": "Account creation timestamp"}
  },
  "required": ["id", "name", "email"]
}

Return ONLY the JSON Schema object - no explanations or markdown formatting.`,
          user: result,
        },
        schema: {
          type: "object",
          description: "JSON Schema7",
          properties: {},
          additionalProperties: true,
        },
      }).then((res) => {
        setAdvancedJson(JSON.stringify(res, null, 2));
      }),
      {
        loading: t("Workflow.generatingJsonSchemaWithAI"),
        success: t("Workflow.jsonSchemaGeneratedSuccessfully"),
        error: t("Workflow.failedToGenerateSchema"),
      },
    );
  }, [t]);

  const updateField = useCallback(
    (index: number, field: Feild) => {
      const newProperties = { ...localSchema.properties };
      const oldKey = fields[index]?.key;

      if (oldKey && oldKey !== field.key) {
        delete newProperties[oldKey];
      }

      newProperties[field.key] = {
        type: field.type,
        ...(field.description && { description: field.description }),
        ...(field.enum && { enum: field.enum }),
        ...(field.defaultValue !== undefined && {
          default: field.defaultValue,
        }),
      };

      const newRequired =
        localSchema.required?.filter((key) => key !== oldKey) || [];
      if (field.required && !newRequired.includes(field.key)) {
        newRequired.push(field.key);
      }

      setLocalSchema({
        ...localSchema,
        properties: newProperties,
        required: newRequired.length > 0 ? newRequired : undefined,
      });
    },
    [fields, localSchema],
  );

  const removeField = useCallback(
    (key: string) => {
      const newProperties = { ...localSchema.properties };
      delete newProperties[key];

      const newRequired = localSchema.required?.filter((k) => k !== key);

      setLocalSchema({
        ...localSchema,
        properties: newProperties,
        required: newRequired?.length ? newRequired : undefined,
      });
    },
    [localSchema],
  );

  useEffect(() => {
    if (open) {
      const is = isObjectJsonSchema7(schema);
      setLocalSchema(is ? schema : structuredClone(defaultObjectJsonSchema));
      setMode("simple");
      setAdvancedJson(is ? JSON.stringify(schema, null, 2) : "");
    }
  }, [open, schema]);

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogTrigger asChild>{children}</DialogTrigger>
      <DialogContent className="max-w-4xl max-h-[90vh] overflow-hidden flex flex-col">
        <DialogHeader>
          <DialogTitle>{t("Workflow.outputSchemaEditor")}</DialogTitle>
        </DialogHeader>

        <div className="flex-1 overflow-hidden">
          <Tabs
            value={mode}
            onValueChange={(v) => setMode(v as SchemaEditMode)}
            className="h-full flex flex-col"
          >
            <TabsList className="grid w-full grid-cols-2">
              <TabsTrigger value="simple" className="flex items-center gap-2">
                <FileTextIcon className="h-4 w-4" />
                Simple
              </TabsTrigger>
              <TabsTrigger value="advanced" className="flex items-center gap-2">
                <CodeIcon className="h-4 w-4" />
                JSON Schema
              </TabsTrigger>
            </TabsList>

            <div className="flex-1 overflow-hidden mt-4 min-h-80">
              <TabsContent value="simple" className="h-full overflow-y-auto">
                <Card className="border-none bg-transparent">
                  <CardHeader className="sr-only">
                    <CardTitle>Schema Fields</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-2 px-0!">
                    {fields.map((field, index) => (
                      <div
                        key={field.key || index}
                        className="flex items-center border rounded-lg px-4 py-2"
                      >
                        <VariableIcon className="size-4 text-blue-500" />
                        <div className="flex-1 flex items-center gap-2 text-sm">
                          <div className="text-muted-foreground w-12">
                            {field.type}
                          </div>
                          <div>
                            <span className="font-medium truncate">
                              {field.key || "unnamed"}
                            </span>
                            {field.required && (
                              <span className="text-destructive ml-1">*</span>
                            )}
                          </div>
                        </div>
                        {["string", "number", "boolean"].includes(
                          field.type,
                        ) && (
                          <EditJsonSchemaFieldPopup
                            field={field}
                            onChange={(updatedField) =>
                              updateField(index, updatedField)
                            }
                          >
                            <Button variant="ghost" size="icon">
                              <PencilIcon />
                            </Button>
                          </EditJsonSchemaFieldPopup>
                        )}

                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => removeField(field.key)}
                          className="hover:text-destructive"
                        >
                          <TrashIcon />
                        </Button>
                      </div>
                    ))}

                    <EditJsonSchemaFieldPopup
                      onChange={(field) => {
                        const newProperties = { ...localSchema.properties };
                        newProperties[field.key] = {
                          type: field.type,
                          ...(field.description && {
                            description: field.description,
                          }),
                          ...(field.enum && { enum: field.enum }),
                          ...(field.defaultValue !== undefined && {
                            default: field.defaultValue,
                          }),
                        };

                        const newRequired = localSchema.required || [];
                        if (
                          field.required &&
                          !newRequired.includes(field.key)
                        ) {
                          newRequired.push(field.key);
                        }

                        setLocalSchema({
                          ...localSchema,
                          properties: newProperties,
                          required:
                            newRequired.length > 0 ? newRequired : undefined,
                        });
                      }}
                    >
                      <Button
                        variant="outline"
                        className="w-full border-dashed"
                      >
                        <PlusIcon className="mr-2" />
                        {t("Workflow.addField")}
                      </Button>
                    </EditJsonSchemaFieldPopup>
                  </CardContent>
                </Card>
              </TabsContent>

              <TabsContent value="advanced" className="h-full overflow-y-auto">
                <Card className="border-none bg-transparent">
                  <CardHeader>
                    <CardTitle>JSON Schema Editor</CardTitle>
                    <CardDescription className="text-sm text-muted-foreground">
                      {t("Workflow.jsonSchemaEditorDescription")}
                    </CardDescription>
                  </CardHeader>

                  <CardContent className="px-0">
                    <div>
                      <div className="flex items-center justify-between mb-2">
                        <Label htmlFor="advanced-json">
                          JSON Schema (Draft 7)
                        </Label>
                        <Button
                          onClick={handleGenerateWithAI}
                          variant="outline"
                          size="sm"
                        >
                          <WandSparklesIcon className="size-3.5 mr-2" />
                          {t("Common.generateWithAI")}
                        </Button>
                      </div>
                      <Textarea
                        id="advanced-json"
                        className="min-h-[300px] font-mono text-sm resize-none max-h-[400px] overflow-y-auto"
                        placeholder={placeholderJsonSchema}
                        value={advancedJson}
                        onChange={(e) => setAdvancedJson(e.target.value)}
                      />
                    </div>
                  </CardContent>
                </Card>
              </TabsContent>
            </div>
          </Tabs>
        </div>

        <DialogFooter>
          <DialogClose asChild>
            <Button variant="ghost">{t("Common.cancel")}</Button>
          </DialogClose>
          <Button onClick={handleSave}>{t("Workflow.saveSchema")}</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

// Helper functions
function getFieldType(schema: JSONSchema7): "string" | "number" | "boolean" {
  if (schema.type === "string" && schema.enum) return "string"; // enum is treated as string
  return (schema.type as "string" | "number" | "boolean") || "string";
}