All files / apps/web/src/backoffice/pages KnowledgeBaseEdit.jsx

0% Statements 0/179
0% Branches 0/245
0% Functions 0/67
0% Lines 0/165

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
import { useState, useEffect } from 'react';
import { useNavigate, useParams, Link } from 'react-router-dom';
import { 
  ArrowLeft, 
  Database, 
  Layers,
  Save,
  Trash2,
  BarChart3,
  FileText,
  RefreshCw,
  AlertCircle,
  Settings,
  Brain,
  CheckCircle,
  XCircle,
  Copy,
  Check,
  Eye,
  EyeOff,
  Code,
  Play,
  Table,
  MessageSquare,
  Network,
  Eraser
} from 'lucide-react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import api from '../../services/api';
import SchemaEditor, { createInitialFields, fieldsToSchemaWithRoot, parseSchema, getSchemaFieldPaths } from '../../components/SchemaEditor';
import toast from 'react-hot-toast';
import { useOrganizationStore } from '../../store/organizationStore';
import KnowledgeBaseSidebar from '../components/KnowledgeBaseSidebar';
import SemanticSourcesEditor from '../components/SemanticSourcesEditor';
import BackofficeEntityPage from '../components/BackofficeEntityPage';
 
 
export default function KnowledgeBaseEdit() {
  const navigate = useNavigate();
  const { id } = useParams();
  const { currentOrganization } = useOrganizationStore();
  const organizationId = currentOrganization?.id;
  const queryClient = useQueryClient();
  const isNew = id === 'new';
 
  const [formData, setFormData] = useState({
    name: '',
    description: '',
    kbType: 'assertion',
    defaultPrompt: '',
    schemaFields: createInitialFields(),
    searchableFields: ['*'],
    mergeOnIngest: true
  });
 
  const [createType, setCreateType] = useState('real');
  const [virtualForm, setVirtualForm] = useState({ name: '', description: '', kbIds: [] });
  // Sources OWL/SHACL saisies à la création d'une KB sémantique (bufferisées).
  const [semanticSources, setSemanticSources] = useState({ ontologySources: [], shapesSources: [] });
  // Sources OWL/SHACL saisies à la création d'une KB sémantique.
 
  const [showStats, setShowStats] = useState(false);
  const [showApiKey, setShowApiKey] = useState(false);
  const [copiedIndex, setCopiedIndex] = useState(null);
 
  const { data: kbs } = useQuery({
    queryKey: ['knowledge-bases', organizationId],
    queryFn: async () => {
      const response = await api.get('/knowledge-bases');
      return response.data.data?.knowledge_bases || response.data || [];
    }
  });
 
  // Fetch KB if editing
const { data: kb, isLoading } = useQuery({
    queryKey: ['knowledge-base', id],
    queryFn: async () => {
      if (isNew) return null;
      const response = await api.get(`/knowledge-bases/${id}`);
      return response.data.data?.knowledge_base || response.data.data;
    },
    enabled: !isNew
  });
 
  const { data: kbStats } = useQuery({
    queryKey: ['knowledge-base-stats', id],
    queryFn: async () => {
      if (isNew) return null;
      const response = await api.get(`/knowledge-bases/${id}/stats`);
      return response.data.data;
    },
    enabled: !isNew
  });
 
  // Fetch API connection info
  const { data: apiInfo } = useQuery({
    queryKey: ['knowledge-base-api-info', id],
    queryFn: async () => {
      if (isNew) return null;
      const response = await api.get(`/knowledge-bases/${id}/api-info`);
      return response.data;
    },
    enabled: !isNew
  });
 
  const copyToClipboard = async (text, index) => {
    try {
      await navigator.clipboard.writeText(text);
      setCopiedIndex(index);
      toast.success('Copié dans le presse-papier');
      setTimeout(() => setCopiedIndex(null), 2000);
    } catch {
      toast.error('Erreur de copie');
    }
  };
 
  // Update form when KB loads
  useEffect(() => {
    if (kb) {
      let schemaFields = createInitialFields();
      if (kb.type === 'data' && kb.schema) {
        schemaFields = parseSchema(kb.schema);
      }
      setFormData({
        name: kb.name || '',
        description: kb.description || '',
        kbType: kb.type || 'assertion',
        defaultPrompt: kb.defaultPrompt || '',
        schemaFields,
        searchableFields: kb.searchableFields && kb.searchableFields.length > 0 ? kb.searchableFields : ['*'],
        mergeOnIngest: kb.mergeOnIngest !== undefined ? kb.mergeOnIngest : true
      });
    }
  }, [kb]);
 
  // Enregistre les sources OWL/SHACL saisies à la création d'une KB sémantique.
  const registerSemanticSources = async (kbId) => {
    const post = async (kind, sources) => {
      for (const s of sources || []) {
        if (s.libraryId) {
          await api.post(`/semantic-kbs/${kbId}/${kind}`, { libraryId: s.libraryId });
        } else if (s.key) {
          await api.post(`/semantic-kbs/${kbId}/${kind}`, { key: s.key, name: s.name, format: s.format || 'turtle' });
        }
      }
    };
    await post('ontology', semanticSources.ontologySources);
    await post('shapes', semanticSources.shapesSources);
  };
 
  // Save mutation. Les 3 types sont créés depuis ce même écran (sélecteur de type).
  const saveKb = useMutation({
    mutationFn: async (data) => {
      const payload = {
        name: data.name,
        description: data.description,
        organizationId
      };
 
      if (isNew) {
        // KB sémantique : créée dans le semantic-kb-service (sources enregistrées ensuite).
        if (data.kbType === 'semantic') {
          return api.post('/semantic-kbs', payload);
        }
        payload.type = data.kbType;
        if (data.kbType === 'assertion') {
          payload.defaultPrompt = data.defaultPrompt;
        } else {
          payload.schema = fieldsToSchemaWithRoot(data.schemaFields);
          payload.searchableFields = data.searchableFields || ['*'];
        }
        payload.mergeOnIngest = data.mergeOnIngest;
        return api.post('/knowledge-bases', payload);
      } else {
        if (kb?.type === 'assertion') {
          payload.defaultPrompt = data.defaultPrompt;
        } else {
          payload.schema = fieldsToSchemaWithRoot(data.schemaFields);
          payload.searchableFields = data.searchableFields || ['*'];
        }
        payload.mergeOnIngest = data.mergeOnIngest;
        return api.patch(`/knowledge-bases/${id}`, payload).catch(() => {
          return api.put(`/knowledge-bases/${id}`, payload);
        });
      }
    },
    onSuccess: async (response, variables) => {
      toast.success(isNew ? 'Base de connaissances créée' : 'Base de connaissances mise à jour');
      queryClient.invalidateQueries(['knowledge-bases']);
      queryClient.invalidateQueries(['semantic-kbs']);
 
      // KB sémantique créée : enregistrer les sources puis ouvrir son éditeur.
      if (isNew && variables?.kbType === 'semantic') {
        const created = response?.data?.data?.semantic_kb;
        if (created?._id) {
          try {
            await registerSemanticSources(created._id);
          } catch (e) {
            toast.error("Erreur lors de l'ajout des ontologies/shapes");
          }
          navigate(`/${organizationId}/backoffice/knowledge/semantic/${created._id}`);
        } else {
          navigate(`/${organizationId}/backoffice/knowledge`);
        }
        return;
      }
 
      if (!isNew) {
        queryClient.invalidateQueries(['knowledge-base-config', id]);
      }
 
      navigate(`/${organizationId}/backoffice/knowledge`);
    },
    onError: (error) => {
      toast.error(error.response?.data?.message || 'Erreur lors de la sauvegarde');
    }
  });
 
  const toggleKb = (kbId) => {
    setVirtualForm(f => ({
      ...f,
      kbIds: f.kbIds.includes(kbId) ? f.kbIds.filter(x => x !== kbId) : [...f.kbIds, kbId]
    }));
  };
 
  const saveVirtual = useMutation({
    mutationFn: async (data) => api.post(`/${organizationId}/virtual-kbs`, data),
    onSuccess: () => {
      toast.success('Base virtuelle créée');
      queryClient.invalidateQueries(['virtual-kbs']);
      navigate(`/${organizationId}/backoffice/knowledge`);
    },
    onError: (e) => toast.error(e.response?.data?.message || 'Erreur lors de la création')
  });
 
  // Delete mutation
  const deleteKb = useMutation({
    mutationFn: async () => {
      return api.delete(`/knowledge-bases/${id}`);
    },
    onSuccess: () => {
      toast.success('Base de connaissances supprimée');
      queryClient.invalidateQueries(['knowledge-bases']);
      navigate(`/${organizationId}/backoffice/knowledge`);
    }
  });
 
  // Vide le CONTENU de la base (assertions / documents) sans la supprimer.
  const emptyKb = useMutation({
    mutationFn: async () => api.delete(`/knowledge-bases/${id}/documents`),
    onSuccess: () => {
      toast.success('Base vidée');
      queryClient.invalidateQueries(['knowledge-bases']);
      queryClient.invalidateQueries(['knowledge-base-stats', id]);
    },
    onError: (error) => {
      toast.error(error.response?.data?.message || 'Impossible de vider la base');
    }
  });
 
  // Reindex mutation
  const reindexKb = useMutation({
    mutationFn: async () => {
      return api.post(`/knowledge-bases/${id}/reindex`);
    },
    onSuccess: (response) => {
      toast.success(response.data?.message || 'Réindexation terminée');
      queryClient.invalidateQueries(['knowledge-base-config', id]);
      queryClient.invalidateQueries(['knowledge-base-stats', id]);
    },
    onError: (error) => {
      toast.error(error.response?.data?.message || 'Réindexation non disponible');
    }
  });
 
  const handleSubmit = (e) => {
    e.preventDefault();
    if (isNew && createType === 'virtual') {
      if (!virtualForm.name.trim()) return toast.error('Veuillez saisir un nom');
      saveVirtual.mutate(virtualForm);
      return;
    }
    saveKb.mutate(formData);
  };
 
  const handleHeaderSubmit = () => {
    if (isNew && createType === 'virtual') {
      if (!virtualForm.name.trim()) return toast.error('Veuillez saisir un nom');
      saveVirtual.mutate(virtualForm);
      return;
    }
    saveKb.mutate(formData);
  };
 
  // ============================================================================
  // API Key section
  // ============================================================================
 
  const { data: apiKeys } = useQuery({
    queryKey: ['api-keys'],
    queryFn: async () => {
      const response = await api.get('/api-keys');
      return response.data.data || [];
    }
  });
 
 
  const handleChange = (field, value) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }));
  };
 
  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600"></div>
      </div>
    );
  }
 
  const embedderIsConfigured = kbStats?.embedder?.isConfigured === true;
  const embedderModel = kbStats?.embedder?.model;
 
  return (
    <BackofficeEntityPage selectedId={isNew ? null : id} sidebar={<KnowledgeBaseSidebar selectedId={isNew ? null : id} />}>
      <div className="flex-1 min-h-0 overflow-y-auto p-3 sm:p-6">
        <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-wrap justify-end gap-2">
        {!isNew && (
          <>
            <Link
              to={`/${organizationId}/knowledge-base/${id}`}
              className="flex items-center px-2 py-2 text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50"
              title="Ouvrir dans le frontoffice"
            >
              <Play className="w-4 h-4" />
            </Link>
            <button
              onClick={() => reindexKb.mutate()}
              disabled={reindexKb.isLoading}
              className="flex items-center px-3 py-2 text-indigo-600 border border-indigo-300 rounded-lg hover:bg-indigo-50 disabled:opacity-50"
            >
              <RefreshCw className={`w-4 h-4 mr-2 ${reindexKb.isLoading ? 'animate-spin' : ''}`} />
              Réindexer
            </button>
            <button
              onClick={() => setShowStats(true)}
              className="flex items-center px-3 py-2 text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50"
            >
              <BarChart3 className="w-4 h-4 mr-2" />
              Statistiques
            </button>
            {kb?.type !== 'virtual' && (
              <button
                onClick={() => {
                  if (window.confirm(`Vider « ${kb?.name || formData.name} » ? Le contenu sera supprimé.`)) {
                    emptyKb.mutate();
                  }
                }}
                disabled={emptyKb.isLoading}
                className="flex items-center px-3 py-2 text-amber-600 border border-amber-300 rounded-lg hover:bg-amber-50 disabled:opacity-50"
              >
                <Eraser className="w-4 h-4 mr-2" />
                Vider
              </button>
            )}
            <button
              onClick={() => {
                if (window.confirm(`Supprimer « ${kb?.name || formData.name} » ? Cette action est irréversible.`)) {
                  deleteKb.mutate();
                }
              }}
              className="flex items-center px-3 py-2 text-red-600 border border-red-300 rounded-lg hover:bg-red-50"
            >
              <Trash2 className="w-4 h-4 mr-2" />
              Supprimer
            </button>
          </>
        )}
        <button
          onClick={handleHeaderSubmit}
          disabled={saveKb.isLoading || saveVirtual.isLoading}
          className="flex items-center px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 disabled:opacity-50"
        >
          <Save className="w-5 h-5 mr-2" />
          {(saveKb.isLoading || saveVirtual.isLoading) ? 'Sauvegarde...' : isNew ? 'Créer' : 'Sauvegarder'}
        </button>
      </div>
 
      {isNew && (
        <div className="bg-white rounded-lg shadow p-6">
          <h3 className="text-lg font-medium text-gray-900 mb-4">Type de base</h3>
          <div className="flex flex-col sm:flex-row gap-3">
            <div className="flex-1 space-y-2">
              <button
                onClick={() => setCreateType('real')}
                className={`w-full flex items-center justify-center gap-2 p-4 rounded-lg border-2 transition-all ${
                  createType === 'real'
                    ? 'border-green-500 bg-green-50 text-green-700'
                    : 'border-gray-200 text-gray-600 hover:bg-gray-50'
                }`}
              >
                <Database className="w-5 h-5" />
                Base réelle
              </button>
              {createType === 'real' && (
                <div className="flex gap-2">
                  <button
                    type="button"
                    onClick={() => setFormData(f => ({ ...f, kbType: 'assertion' }))}
                    className={`flex-1 flex items-center justify-center gap-2 p-3 rounded-lg border-2 transition-all ${
                      formData.kbType === 'assertion'
                        ? 'border-purple-500 bg-purple-50 text-purple-700'
                        : 'border-gray-200 text-gray-600 hover:bg-gray-50'
                    }`}
                  >
                    <MessageSquare className="w-4 h-4" />
                    Assertions
                  </button>
                  <button
                    type="button"
                    onClick={() => setFormData(f => ({ ...f, kbType: 'data' }))}
                    className={`flex-1 flex items-center justify-center gap-2 p-3 rounded-lg border-2 transition-all ${
                      formData.kbType === 'data'
                        ? 'border-indigo-500 bg-indigo-50 text-indigo-700'
                        : 'border-gray-200 text-gray-600 hover:bg-gray-50'
                    }`}
                  >
                    <Table className="w-4 h-4" />
                    Data
                  </button>
                  <button
                    type="button"
                    onClick={() => setFormData(f => ({ ...f, kbType: 'semantic' }))}
                    className={`flex-1 flex items-center justify-center gap-2 p-3 rounded-lg border-2 transition-all ${
                      formData.kbType === 'semantic'
                        ? 'border-teal-500 bg-teal-50 text-teal-700'
                        : 'border-gray-200 text-gray-600 hover:bg-gray-50'
                    }`}
                  >
                    <Network className="w-4 h-4" />
                    Sémantique
                  </button>
                </div>
              )}
            </div>
            <button
              onClick={() => setCreateType('virtual')}
              className={`flex-1 flex items-center justify-center gap-2 p-4 rounded-lg border-2 transition-all ${
                createType === 'virtual'
                  ? 'border-purple-500 bg-purple-50 text-purple-700'
                  : 'border-gray-200 text-gray-600 hover:bg-gray-50'
              }`}
            >
              <Layers className="w-5 h-5" />
              Base virtuelle
            </button>
          </div>
        </div>
      )}
 
      {isNew && createType === 'virtual' ? (
        <div className="bg-white rounded-lg shadow p-6 space-y-4">
          <div className="flex items-center mb-4">
            <Layers className="w-6 h-6 text-purple-600 mr-2" />
            <h3 className="text-lg font-medium text-gray-900">Informations</h3>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Nom de la base virtuelle *</label>
            <input
              type="text"
              value={virtualForm.name}
              onChange={(e) => setVirtualForm(f => ({ ...f, name: e.target.value }))}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
              placeholder="Ex: Toute la documentation"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Description</label>
            <input
              type="text"
              value={virtualForm.description}
              onChange={(e) => setVirtualForm(f => ({ ...f, description: e.target.value }))}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
              placeholder="Description (optionnelle)"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">Bases de connaissances incluses</label>
            <div className="max-h-60 overflow-y-auto border border-gray-200 rounded-lg divide-y">
              {(kbs || []).map(kb => (
                <label key={kb._id} className="flex items-center p-3 hover:bg-gray-50 cursor-pointer">
                  <input type="checkbox" checked={virtualForm.kbIds.includes(kb._id)} onChange={() => toggleKb(kb._id)} className="mr-3" />
                  <Database className="w-4 h-4 text-green-500 mr-2" />
                  <span className="text-sm font-medium text-gray-900">{kb.name}</span>
                  <span className="ml-auto text-xs text-gray-400">{(kb.assertion_count ?? kb.fact_count) || 0} assertions</span>
                </label>
              ))}
              {(!kbs || kbs.length === 0) && <p className="text-sm text-gray-400 p-4 text-center">Aucune base réelle disponible</p>}
            </div>
            {virtualForm.kbIds.length > 0 && (
              <p className="text-xs text-gray-500 mt-2">
                {virtualForm.kbIds.length} KB{virtualForm.kbIds.length > 1 ? 's' : ''} sélectionnée{virtualForm.kbIds.length > 1 ? 's' : ''}
              </p>
            )}
          </div>
        </div>
      ) : (
      <form onSubmit={handleSubmit} className="space-y-6">
        {/* General Info */}
        <div className="bg-white rounded-lg shadow p-6">
          <div className="flex items-center mb-4">
            <Database className="w-6 h-6 text-green-600 mr-2" />
            <h3 className="text-lg font-medium text-gray-900">Informations</h3>
          </div>
          
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Nom de la base *
              </label>
              <input
                type="text"
                value={formData.name}
                onChange={(e) => handleChange('name', e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
                placeholder="Ex: Base Documents Techniques"
                required
              />
            </div>
 
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Description
              </label>
              <textarea
                value={formData.description}
                onChange={(e) => handleChange('description', e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
                placeholder="Description de la base de connaissances..."
                rows={2}
              />
            </div>
 
            <div className="flex items-start justify-between gap-4 rounded-lg border border-gray-200 p-3">
              <div>
                <label className="block text-sm font-medium text-gray-700">
                  Fusionner les entités proches à l'injection
                </label>
                <p className="text-xs text-gray-500 mt-0.5">
                  Activé : une nouvelle assertion/data sémantiquement proche d'une entité existante est fusionnée avec elle.
                  Désactivé : chaque nouvelle assertion/data devient sa propre entité.
                </p>
              </div>
              <input
                type="checkbox"
                checked={formData.mergeOnIngest}
                onChange={(e) => handleChange('mergeOnIngest', e.target.checked)}
                className="h-5 w-5 mt-1"
              />
            </div>
 
            {!isNew && (kb?.type === 'data') && (
              <div className="flex items-center gap-2">
                <Table className="w-4 h-4 text-indigo-500" />
                <span className="text-sm font-medium text-indigo-700">Base de data</span>
                <span className="text-xs text-gray-500">Documents JSON validés contre le schéma de la base</span>
              </div>
            )}
            {!isNew && (kb?.type === 'assertion' || (!isNew && !kb?.type)) && (
              <div className="flex items-center gap-2">
                <MessageSquare className="w-4 h-4 text-purple-500" />
                <span className="text-sm font-medium text-purple-700">Base d'assertions</span>
                <span className="text-xs text-gray-500">Assertions textuelles</span>
              </div>
            )}
 
            {(!isNew || formData.kbType === 'assertion') && (
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Prompt de raffinage par défaut
                </label>
                <textarea
                  value={formData.defaultPrompt}
                  onChange={(e) => handleChange('defaultPrompt', e.target.value)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
                  placeholder="Prompt proposé quand cette base est choisie comme destination..."
                  rows={2}
                />
                <p className="text-xs text-gray-500 mt-1">
                  Pré-rempli automatiquement lors de la sélection de cette base comme destination (modifiable).
                </p>
              </div>
            )}
 
            {isNew && formData.kbType === 'data' && (
              <div className="border rounded-lg p-4 bg-gray-50">
                <div className="flex items-center justify-between mb-4">
                  <h4 className="font-medium text-gray-900 flex items-center">
                    <Code className="w-4 h-4 mr-2" />
                    Schéma JSON des documents
                  </h4>
                  <span className="text-xs text-gray-500">
                    Les données injectées seront validées contre ce schéma
                  </span>
                </div>
                <SchemaEditor
                  fields={formData.schemaFields}
                  onChange={(fields) => handleChange('schemaFields', fields)}
                  disabled={false}
                />
                <div className="mt-4">
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Champs recherchables
                  </label>
                  <div className="flex flex-col gap-2">
                    <label className="flex items-center gap-2 text-sm text-gray-700">
                      <input
                        type="checkbox"
                        checked={formData.searchableFields?.includes('*')}
                        onChange={(e) => handleChange('searchableFields', e.target.checked ? ['*'] : [])}
                        className="mr-1"
                      />
                      Tous les champs
                    </label>
                    {!formData.searchableFields?.includes('*') && (
                      <div className="flex flex-wrap gap-2">
                        {getSchemaFieldPaths(formData.schemaFields).map(path => (
                          <label key={path} className="flex items-center gap-1 text-sm text-gray-600 bg-white border border-gray-200 rounded-lg px-3 py-1.5">
                            <input
                              type="checkbox"
                              checked={formData.searchableFields?.includes(path)}
                              onChange={(e) => {
                                const current = formData.searchableFields?.includes('*') ? [] : (formData.searchableFields || []);
                                const next = e.target.checked ? [...current, path] : current.filter(p => p !== path);
                                handleChange('searchableFields', next);
                              }}
                              className="mr-1"
                            />
                            <span className="font-mono text-xs">{path}</span>
                          </label>
                        ))}
                      </div>
                    )}
                  </div>
                </div>
              </div>
            )}
 
            {isNew && formData.kbType === 'semantic' && (
              <SemanticSourcesEditor
                organizationId={organizationId}
                value={semanticSources}
                onChange={setSemanticSources}
                hint="Ontologies et contraintes SHACL utilisées pour le raffinage vers cette KB (mêmes sources que dans l'éditeur)."
              />
            )}
 
            {!isNew && kb?.type === 'data' && (
              <div className="border rounded-lg p-4 bg-gray-50">
                <h4 className="font-medium text-gray-900 flex items-center mb-2">
                  <Code className="w-4 h-4 mr-2" />
                  Schéma JSON (lecture seule)
                </h4>
                <SchemaEditor fields={formData.schemaFields} onChange={() => {}} disabled={true} />
                <p className="text-xs text-gray-500 mt-2">
                  Le schéma est défini à la création de la base. Les destinations ne peuvent pas le modifier.
                  {formData.searchableFields?.includes('*')
                    ? ' Recherche : tous les champs.'
                    : ` Champs recherchables : ${formData.searchableFields?.join(', ') || 'aucun'}.`}
                </p>
              </div>
            )}
 
            <div className="flex items-center space-x-4">
              {!isNew && kbStats && (
                <div className="flex items-center">
                  <FileText className="w-4 h-4 text-gray-400 mr-2" />
                  <span className="text-sm text-gray-600">
                    {kbStats?.knowledge_base?.meilisearchStats?.numberOfDocuments?.toLocaleString() || 0} éléments indexés
                  </span>
                </div>
              )}
            </div>
          </div>
        </div>
 
        {/* Embedding Configuration */}
        {!isNew && (
          <div className="bg-white rounded-lg shadow p-6">
            <div className="flex flex-wrap items-center gap-2 mb-4">
              <Brain className="w-6 h-6 text-purple-600 mr-2 flex-shrink-0" />
              <h3 className="text-lg font-medium text-gray-900">Configuration Embedding</h3>
              <span className={`inline-flex items-center px-2 py-1 rounded text-xs font-medium ${
                embedderIsConfigured 
                  ? 'bg-green-100 text-green-700' 
                  : 'bg-yellow-100 text-yellow-700'
              }`}>
                {embedderIsConfigured ? (
                  <>
                    <CheckCircle className="w-3 h-3 mr-1" />
                    Configuré
                  </>
                ) : (
                  <>
                    <XCircle className="w-3 h-3 mr-1" />
                    Non configuré
                  </>
                )}
              </span>
              <button
                onClick={() => reindexKb.mutate()}
                disabled={reindexKb.isLoading}
                className="flex items-center px-3 py-1.5 text-sm bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 disabled:opacity-50"
              >
                <RefreshCw className={`w-3 h-3 mr-1 ${reindexKb.isLoading ? 'animate-spin' : ''}`} />
                {reindexKb.isLoading ? 'Réindexation...' : embedderIsConfigured ? 'Réindexer' : 'Configurer + indexer'}
              </button>
            </div>
            
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div className="space-y-3">
                {embedderIsConfigured && (
                  <div>
                    <label className="block text-xs font-medium text-gray-500 uppercase tracking-wide mb-1">
                      Modèle d'Embedding
                    </label>
                    <div className="flex items-center">
                      <span className="px-3 py-2 bg-purple-50 text-purple-700 rounded-lg font-mono text-sm">
                        {embedderModel}
                      </span>
                    </div>
                  </div>
                )}
 
                {embedderIsConfigured && (
                  <>
                    <div>
                      <label className="block text-xs font-medium text-gray-500 uppercase tracking-wide mb-1">
                        Provider
                      </label>
                      <div className="flex items-center">
                        <span className="px-3 py-2 bg-blue-50 text-blue-700 rounded-lg text-sm">
                          OpenRouter API
                        </span>
                      </div>
                    </div>
 
                    <div>
                      <label className="block text-xs font-medium text-gray-500 uppercase tracking-wide mb-1">
                        Template Document
                      </label>
                      <div className="px-3 py-2 bg-gray-50 text-gray-700 rounded-lg font-mono text-sm">
                        {kbStats?.embedder?.documentTemplate || '{{text}}'}
                      </div>
                    </div>
                  </>
                )}
              </div>
 
              <div className="space-y-3">
                <div>
                  <label className="block text-xs font-medium text-gray-500 uppercase tracking-wide mb-1">
                    Attributs Indexés
                  </label>
                  <div className="flex flex-wrap gap-2">
                    {(kbStats?.index_config?.searchableAttributes || ['text']).map((attr, idx) => (
                      <span key={idx} className="px-2 py-1 bg-indigo-100 text-indigo-700 rounded text-sm">
                        {attr}
                      </span>
                    ))}
                  </div>
                </div>
 
                <div>
                  <label className="block text-xs font-medium text-gray-500 uppercase tracking-wide mb-1">
                    Attributs Filtrables
                  </label>
                  <div className="flex flex-wrap gap-2">
                    {(kbStats?.index_config?.filterableAttributes || ['source', 'timestamp', 'confidence']).map((attr, idx) => (
                      <span key={idx} className="px-2 py-1 bg-gray-100 text-gray-700 rounded text-sm">
                        {attr}
                      </span>
                    ))}
                  </div>
                </div>
 
                <div>
                  <label className="block text-xs font-medium text-gray-500 uppercase tracking-wide mb-1">
                    Type de Recherche
                  </label>
                  <div className="flex flex-wrap gap-2">
                    <span className="px-2 py-1 bg-green-100 text-green-700 rounded text-sm">
                      fulltext
                    </span>
                    <span className="px-2 py-1 bg-purple-100 text-purple-700 rounded text-sm">
                      semantic
                    </span>
                    <span className="px-2 py-1 bg-blue-100 text-blue-700 rounded text-sm">
                      hybrid
                    </span>
                  </div>
                </div>
              </div>
            </div>
 
            <div className="mt-4 p-4 bg-yellow-50 rounded-lg flex items-start">
              <AlertCircle className="w-5 h-5 text-yellow-600 mr-2 mt-0.5" />
              <div className="text-sm text-yellow-700">
                <strong>Recherche Hybrid:</strong> Activez la recherche sémantique pour améliorer les résultats 
                en combinant recherche par mots-clés et par similarité vectorielle.
              </div>
            </div>
          </div>
        )}
 
        {/* API Endpoints */}
        {!isNew && apiInfo && (
          <div className="bg-white rounded-lg shadow p-6">
            <div className="flex items-center mb-4">
              <Code className="w-6 h-6 text-blue-600 mr-2" />
              <h3 className="text-lg font-medium text-gray-900">API Endpoints</h3>
            </div>
 
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              {/* Raw Meilisearch API */}
              <div className="border border-gray-200 rounded-lg p-4">
                <div className="flex items-center mb-3">
                  <Database className="w-5 h-5 text-orange-500 mr-2" />
                  <h4 className="font-medium text-gray-900">Meilisearch (brut)</h4>
                  <span className="ml-2 px-2 py-0.5 bg-orange-100 text-orange-700 text-xs rounded">API directe</span>
                </div>
 
                <div className="space-y-2 text-sm">
                  <div className="flex justify-between items-start">
                    <span className="text-gray-500 flex-shrink-0">URL</span>
                    <span className="font-mono text-xs text-gray-900 truncate ml-2 text-right break-all">{apiInfo.meilisearch.searchUrl}</span>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-gray-500">Méthode</span>
                    <span className="font-mono text-xs text-green-600 font-semibold">POST</span>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-gray-500">Auth</span>
                    <span className="font-mono text-xs text-gray-900">API Key</span>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-gray-500">Headers</span>
                    <span className="font-mono text-xs text-gray-900 truncate ml-2 text-right">x-api-key: &lt;VOTRE_CLE_API&gt;</span>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-gray-500">Body</span>
                    <span className="font-mono text-xs text-gray-900 truncate ml-2 text-right">{'{ "q": string, "limit": number }'}</span>
                  </div>
                </div>
 
                <div className="mt-3">
                  <div className="flex items-center justify-between mb-1">
                    <span className="text-xs font-medium text-gray-500 uppercase">cURL</span>
                    <button
                      type="button"
                      onClick={() => copyToClipboard(apiInfo.meilisearch.curlExample, 'meili')}
                      className="flex items-center text-xs text-indigo-600 hover:text-indigo-800"
                    >
                      {copiedIndex === 'meili' ? (
                        <Check className="w-3 h-3 mr-1" />
                      ) : (
                        <Copy className="w-3 h-3 mr-1" />
                      )}
                      {copiedIndex === 'meili' ? 'Copié' : 'Copier'}
                    </button>
                  </div>
                  <pre className="bg-gray-900 text-green-400 text-xs p-3 rounded-lg overflow-x-auto max-h-32">
                    {apiInfo.meilisearch.curlExample}
                  </pre>
                </div>
              </div>
 
              {/* Nooloom Search API */}
              <div className="border border-gray-200 rounded-lg p-4">
                <div className="flex items-center mb-3">
                  <Code className="w-5 h-5 text-indigo-500 mr-2" />
                  <h4 className="font-medium text-gray-900">Nooloom Search</h4>
                  <span className="ml-2 px-2 py-0.5 bg-indigo-100 text-indigo-700 text-xs rounded">API surchargée</span>
                </div>
 
                <div className="space-y-2 text-sm">
                  <div className="flex justify-between items-start">
                    <span className="text-gray-500 flex-shrink-0">URL</span>
                    <span className="font-mono text-xs text-gray-900 truncate ml-2 text-right break-all">{apiInfo.nooloomSearch.url}</span>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-gray-500">Méthode</span>
                    <span className="font-mono text-xs text-green-600 font-semibold">{apiInfo.nooloomSearch.method}</span>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-gray-500">Auth</span>
                    <span className="font-mono text-xs text-gray-900">API Key</span>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-gray-500">Headers</span>
                    <span className="font-mono text-xs text-gray-900 truncate ml-2 text-right">x-api-key: &lt;VOTRE_CLE_API&gt;</span>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-gray-500">Body</span>
                    <span className="font-mono text-xs text-gray-900 truncate ml-2 text-right">{JSON.stringify(apiInfo.nooloomSearch.body)}</span>
                  </div>
                </div>
 
                <div className="mt-3">
                  <div className="flex items-center justify-between mb-1">
                    <span className="text-xs font-medium text-gray-500 uppercase">cURL</span>
                    <button
                      type="button"
                      onClick={() => copyToClipboard(apiInfo.nooloomSearch.curlExample, 'nooloom')}
                      className="flex items-center text-xs text-indigo-600 hover:text-indigo-800"
                    >
                      {copiedIndex === 'nooloom' ? (
                        <Check className="w-3 h-3 mr-1" />
                      ) : (
                        <Copy className="w-3 h-3 mr-1" />
                      )}
                      {copiedIndex === 'nooloom' ? 'Copié' : 'Copier'}
                    </button>
                  </div>
                  <pre className="bg-gray-900 text-green-400 text-xs p-3 rounded-lg overflow-x-auto max-h-32">
                    {apiInfo.nooloomSearch.curlExample}
                  </pre>
                </div>
              </div>
            </div>
 
            <div className="mt-4 p-3 bg-blue-50 rounded-lg flex items-start">
              <AlertCircle className="w-5 h-5 text-blue-600 mr-2 mt-0.5 flex-shrink-0" />
              <div className="text-sm text-blue-700">
                <strong>Pour les agents IA :</strong> Les deux APIs supportent l'authentification par clé d'API (header <code>x-api-key</code>). 
                 Gérez vos clés depuis <strong>Système → Configuration → Clés API Organisation</strong>.
              </div>
            </div>
          </div>
        )}
 
      </form>
      )}
 
      {/* Stats Modal */}
      {showStats && (kbStats || kb) && (
        <div className="fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center p-4 z-50">
          <div className="bg-white rounded-lg max-w-2xl w-full max-h-[90vh] overflow-y-auto">
            <div className="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
              <h3 className="text-lg font-medium text-gray-900">Statistiques: {(kbStats || kb)?.name}</h3>
              <button
                onClick={() => setShowStats(false)}
                className="text-gray-400 hover:text-gray-500"
              >
                <ArrowLeft className="w-6 h-6" />
              </button>
            </div>
            <div className="p-6 space-y-6">
              <div className="text-center p-4 bg-green-50 rounded-lg">
                <p className="text-3xl font-bold text-green-600">
                  {kbStats?.knowledge_base?.meilisearchStats?.numberOfDocuments?.toLocaleString() || 0}
                </p>
                <p className="text-sm text-gray-600">Faits indexés</p>
              </div>
 
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div className={`p-4 rounded-lg ${kbStats?.embedder?.isConfigured ? 'bg-purple-50' : 'bg-yellow-50'}`}>
                  <div className="flex items-center mb-2">
                    <Brain className={`w-5 h-5 mr-2 ${kbStats?.embedder?.isConfigured ? 'text-purple-600' : 'text-yellow-600'}`} />
                    <span className="font-medium text-gray-900">Embeddings</span>
                  </div>
                  {kbStats?.embedder?.isConfigured ? (
                    <div className="text-sm">
                      <p className="text-purple-700 font-mono text-xs">{kbStats.embedder.model}</p>
                      <p className="text-green-600 mt-1 flex items-center">
                        <CheckCircle className="w-4 h-4 mr-1" />
                        Configuré
                      </p>
                    </div>
                  ) : (
                    <div className="text-sm text-yellow-700 flex items-center">
                      <XCircle className="w-4 h-4 mr-1" />
                      Non configuré
                    </div>
                  )}
                </div>
 
                <div className={`p-4 rounded-lg ${kbStats?.knowledge_base?.meilisearchStats?.isIndexing ? 'bg-orange-50' : 'bg-gray-50'}`}>
                  <div className="flex items-center mb-2">
                    <RefreshCw className={`w-5 h-5 mr-2 ${kbStats?.knowledge_base?.meilisearchStats?.isIndexing ? 'text-orange-600 animate-spin' : 'text-gray-400'}`} />
                    <span className="font-medium text-gray-900">Indexation</span>
                  </div>
                  <p className={`text-lg font-bold ${kbStats?.knowledge_base?.meilisearchStats?.isIndexing ? 'text-orange-600' : 'text-green-600'}`}>
                    {kbStats?.knowledge_base?.meilisearchStats?.isIndexing ? 'En cours' : 'Terminée'}
                  </p>
                </div>
              </div>
 
              {kbStats?.knowledge_base?.meilisearchStats?.sizeInBytes > 0 && (
                <div className="p-4 bg-gray-50 rounded-lg">
                  <h4 className="font-medium text-gray-900 mb-3">Ressources Meilisearch</h4>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 text-sm">
                    <div className="flex justify-between p-2 bg-white rounded">
                      <span className="text-gray-600">Taille index</span>
                      <span className="font-medium">{(kbStats.knowledge_base.meilisearchStats.sizeInBytes / 1024 / 1024).toFixed(2)} MB</span>
                    </div>
                    <div className="flex justify-between p-2 bg-white rounded">
                      <span className="text-gray-600">Documents</span>
                      <span className="font-medium">{kbStats.knowledge_base.meilisearchStats.numberOfDocuments?.toLocaleString()}</span>
                    </div>
                    {kbStats.knowledge_base.meilisearchStats.wordCount && (
                      <div className="flex justify-between p-2 bg-white rounded">
                        <span className="text-gray-600">Mots indexés</span>
                        <span className="font-medium">{kbStats.knowledge_base.meilisearchStats.wordCount?.toLocaleString()}</span>
                      </div>
                    )}
                  </div>
                </div>
              )}
 
              <div className="p-4 bg-blue-50 rounded-lg flex items-start">
                <AlertCircle className="w-5 h-5 text-blue-600 mr-2 mt-0.5" />
                <div className="text-sm text-blue-700">
                  <strong>Knowledge Base:</strong> Les assertions sont stockées et indexées dans Meilisearch. 
                  Cliquez sur "Réindexer" si les résultats de recherche ne semblent pas à jour.
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
        </div>
      </div>
    </BackofficeEntityPage>
  );
}