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

0% Statements 0/180
0% Branches 0/198
0% Functions 0/69
0% Lines 0/163

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
import { useState, useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import {
  Network,
  Save,
  Trash2,
  Eraser,
  Play,
  Database,
  Layers,
  Compass,
  AlertTriangle,
  RotateCw,
  Search,
  Link2,
  Plus,
  Loader2,
} from 'lucide-react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import api, { API_URL } from '../../services/api';
import toast from 'react-hot-toast';
import { useOrganizationStore } from '../../store/organizationStore';
import KnowledgeBaseSidebar from '../components/KnowledgeBaseSidebar';
import BackofficeEntityPage from '../components/BackofficeEntityPage';
import YasguiConsole from '../../components/YasguiConsole';
import SemanticGraphViewer from '../../components/SemanticGraphViewer';
import { sparqlResultToRows } from '../../utils/sparql';
import SemanticSourcesEditor from '../components/SemanticSourcesEditor';
import { DEFAULT_NAME_PREDICATES } from '../../config/semanticOntologies';
 
// Les KB sémantiques vivent sous l'entrée de menu « Knowledge Bases ».
const listHref = (organizationId) => `/${organizationId}/backoffice/knowledge/semantic`;
const knowledgeHref = (organizationId) => `/${organizationId}/backoffice/knowledge`;
 
const TABS = [
  { id: 'config', label: 'Configuration', icon: Network },
  { id: 'structure', label: 'Structure (OWL/SHACL)', icon: Layers },
  { id: 'explore', label: 'Explorateur', icon: Compass },
  { id: 'reconcile', label: 'Réconciliation', icon: AlertTriangle },
  { id: 'entities', label: 'Entités', icon: Search },
];
 
export default function SemanticKnowledgeBaseEdit() {
  const navigate = useNavigate();
  const { id } = useParams();
  const { currentOrganization } = useOrganizationStore();
  const organizationId = currentOrganization?.id;
  const queryClient = useQueryClient();
  const isNew = id === 'new';
  const base = listHref(organizationId);
 
  const [tab, setTab] = useState('config');
  const [formData, setFormData] = useState({
    name: '',
    description: '',
    ingestMode: 'review',
    namePredicates: [],
  });
  // Sources OWL/SHACL en cours de création (bufferisées puis enregistrées après création).
  const [pendingSources, setPendingSources] = useState({ ontologySources: [], shapesSources: [] });
  const [namePredicateInput, setNamePredicateInput] = useState('');
  const [sparqlQuery, setSparqlQuery] = useState('SELECT * WHERE { ?s ?p ?o } LIMIT 25');
  const [sparqlResult, setSparqlResult] = useState(null);
  const [exploreMode, setExploreMode] = useState('yasgui');
 
  const { data: kb, isLoading } = useQuery({
    queryKey: ['semantic-kb', id],
    queryFn: async () => {
      if (isNew) return null;
      const response = await api.get(`/semantic-kbs/${id}`);
      return response.data.data?.semantic_kb || response.data.data;
    },
    enabled: !isNew,
  });
 
  useEffect(() => {
    if (kb) {
      setFormData({
        name: kb.name || '',
        description: kb.description || '',
        ingestMode: kb.ingestMode || 'review',
        namePredicates: Array.isArray(kb.namePredicates) ? kb.namePredicates : [],
      });
    }
  }, [kb]);
 
  const invalidate = () => {
    queryClient.invalidateQueries(['semantic-kb', id]);
    queryClient.invalidateQueries(['semantic-kbs']);
  };
 
  // Enregistre les sources bufferisées après la création de la KB.
  const registerPendingSources = 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', pendingSources.ontologySources);
    await post('shapes', pendingSources.shapesSources);
  };
 
  const saveKb = useMutation({
    mutationFn: async (data) => {
      const payload = {
        name: data.name,
        description: data.description,
        ingestMode: data.ingestMode,
        namePredicates: Array.isArray(data.namePredicates) ? data.namePredicates : [],
        organizationId,
      };
      return isNew ? api.post('/semantic-kbs', payload) : api.put(`/semantic-kbs/${id}`, payload);
    },
    onSuccess: async (response) => {
      toast.success(isNew ? 'KB sémantique créée' : 'KB sémantique mise à jour');
      if (isNew) {
        const created = response?.data?.data?.semantic_kb;
        if (created?._id) {
          try {
            await registerPendingSources(created._id);
          } catch (e) {
            toast.error("Erreur lors de l'ajout des ontologies/shapes");
          }
          navigate(`${base}/${created._id}`);
          return;
        }
        navigate(knowledgeHref(organizationId));
        return;
      }
      invalidate();
    },
    onError: (error) => toast.error(error.message || error.response?.data?.message || 'Erreur lors de la sauvegarde'),
  });
 
  // Vide le graphe de données (…:data) sans supprimer la KB (ontologie/SHACL conservés).
  const emptyKb = useMutation({
    mutationFn: async () => api.delete(`/semantic-kbs/${id}/data`),
    onSuccess: () => {
      toast.success('KB vidée');
      invalidate();
    },
    onError: (error) => toast.error(error.response?.data?.message || 'Impossible de vider la KB'),
  });
 
  const deleteKb = useMutation({
    mutationFn: async () => api.delete(`/semantic-kbs/${id}`),
    onSuccess: () => {
      toast.success('KB sémantique supprimée');
      queryClient.invalidateQueries(['semantic-kbs']);
      navigate(knowledgeHref(organizationId));
    },
    onError: (error) => toast.error(error.response?.data?.message || 'Erreur lors de la suppression'),
  });
 
  // --- Sources OWL/SHACL (bibliothèque partagée) ---
  const [savingSources, setSavingSources] = useState(false);
 
  // Réconcilie les sources avec le serveur (ajout/retrait) puis recharge la KB.
  // En création, les sources sont bufferisées (enregistrées après la création).
  const applySourcesChange = async (next) => {
    if (isNew) {
      setPendingSources({ ontologySources: next.ontologySources || [], shapesSources: next.shapesSources || [] });
      return;
    }
    setSavingSources(true);
    try {
      const apply = async (kind, serverSources, nextSources) => {
        const nextIds = new Set((nextSources || []).map((s) => s._id).filter(Boolean));
        for (const s of serverSources || []) {
          if (!nextIds.has(s._id)) await api.delete(`/semantic-kbs/${id}/${kind}/${s._id}`);
        }
        for (const s of nextSources || []) {
          if (s._id) continue;
          if (s.libraryId) await api.post(`/semantic-kbs/${id}/${kind}`, { libraryId: s.libraryId });
          else if (s.key) await api.post(`/semantic-kbs/${id}/${kind}`, { key: s.key, name: s.name, format: s.format || 'turtle' });
        }
      };
      await apply('ontology', kb?.ontologies || [], next.ontologySources || []);
      await apply('shapes', kb?.shapes || [], next.shapesSources || []);
      invalidate();
    } catch (e) {
      toast.error(e.response?.data?.message || 'Erreur lors de la mise à jour des sources');
    } finally {
      setSavingSources(false);
    }
  };
 
  // Liste effective des propriétés de nom (défaut si non personnalisée) + ajout/suppression.
  const effectiveNamePredicates = formData.namePredicates?.length
    ? formData.namePredicates
    : DEFAULT_NAME_PREDICATES;
 
  const setNamePredicates = (list) => setFormData((f) => ({ ...f, namePredicates: list }));
 
  const addNamePredicate = () => {
    const val = namePredicateInput.trim();
    if (!val) return;
    const current = formData.namePredicates?.length ? formData.namePredicates : [...DEFAULT_NAME_PREDICATES];
    if (!current.includes(val)) setNamePredicates([...current, val]);
    setNamePredicateInput('');
  };
 
  const removeNamePredicate = (iri) =>
    setNamePredicates(effectiveNamePredicates.filter((p) => p !== iri));
 
  const runSparql = useMutation({
    mutationFn: async () => api.post(`/semantic-kbs/${id}/sparql`, { query: sparqlQuery }),
    onSuccess: (res) => setSparqlResult(sparqlResultToRows(res.data)),
    onError: (error) => toast.error(error.response?.data?.message || 'Requête SPARQL refusée'),
  });
 
  // --- Réconciliation (P3) : conflits, entités, ré-indexation ---
  const [entityQuery, setEntityQuery] = useState('');
  const [entities, setEntities] = useState([]);
 
  const { data: conflicts = [], refetch: refetchConflicts } = useQuery({
    queryKey: ['semantic-kb-conflicts', id],
    queryFn: async () => {
      const r = await api.get(`/semantic-kbs/${id}/conflicts`);
      return r.data.data?.conflicts || [];
    },
    enabled: !isNew && tab === 'reconcile',
  });
 
  // Résolution PAR LIGNE : { [conflictId]: action } — plusieurs fusions possibles en parallèle.
  const [pending, setPending] = useState({});
  const resolveConflict = async ({ conflictId, action }) => {
    setPending((p) => ({ ...p, [conflictId]: action }));
    try {
      await api.post(`/semantic-kbs/${id}/conflicts/${conflictId}/resolve`, { action });
      toast.success('Conflit traité');
      refetchConflicts();
      invalidate();
    } catch (error) {
      toast.error(error.response?.data?.message || 'Impossible de traiter le conflit');
    } finally {
      setPending((p) => {
        const next = { ...p };
        delete next[conflictId];
        return next;
      });
    }
  };
 
  const reindexKb = useMutation({
    mutationFn: async () => api.post(`/semantic-kbs/${id}/reindex`),
    onSuccess: (r) => toast.success(`${r.data.data?.reindexed ?? 0} entité(s) ré-indexée(s)`),
    onError: (error) => toast.error(error.response?.data?.message || 'Réindexation impossible'),
  });
 
  const searchEntities = useMutation({
    mutationFn: async (q) => api.get(`/semantic-kbs/${id}/entities`, { params: { q } }),
    onSuccess: (r) => setEntities(r.data.data?.entities || []),
    onError: () => toast.error('Recherche impossible'),
  });
 
  // Sidebar partagée avec l'éditeur de KB standard (mêmes entrées, même ergonomie).
  const sidebar = <KnowledgeBaseSidebar selectedId={isNew ? null : id} />;
 
  const tabButton = (t) => {
    const Icon = t.icon;
    const active = tab === t.id;
    return (
      <button
        key={t.id}
        type="button"
        onClick={() => setTab(t.id)}
        disabled={isNew && !['config', 'structure'].includes(t.id)}
        className={`flex items-center gap-2 px-3 py-2 text-sm rounded-lg border-2 transition-all disabled:opacity-40 ${
          active ? 'border-teal-500 bg-teal-50 text-teal-700' : 'border-transparent text-gray-600 hover:bg-gray-50'
        }`}
      >
        <Icon className="w-4 h-4" />
        {t.label}
      </button>
    );
  };
 
  return (
    <BackofficeEntityPage selectedId={isNew ? null : id} sidebar={sidebar}>
      <div className="flex-1 min-h-0 overflow-y-auto p-3 sm:p-6">
        <div className="space-y-6">
          <div className="flex flex-wrap justify-between gap-2">
            <div className="flex flex-wrap gap-1">{TABS.map(tabButton)}</div>
            <div className="flex gap-2">
              {!isNew && (
                <button
                  onClick={() => {
                    if (window.confirm(`Vider « ${kb?.name || formData.name} » ? Les triplets de données seront supprimés (ontologie et SHACL conservés).`)) {
                      emptyKb.mutate();
                    }
                  }}
                  disabled={emptyKb.isLoading}
                  className="flex items-center px-4 py-2 text-amber-600 border border-amber-300 rounded-lg hover:bg-amber-50 disabled:opacity-50"
                >
                  <Eraser className="w-5 h-5 mr-2" />
                  Vider
                </button>
              )}
              {!isNew && (
                <button
                  onClick={() => {
                    if (window.confirm(`Supprimer « ${kb?.name || formData.name} » ? Cette action est irréversible.`)) {
                      deleteKb.mutate();
                    }
                  }}
                  className="flex items-center px-4 py-2 text-red-600 border border-red-300 rounded-lg hover:bg-red-50"
                >
                  <Trash2 className="w-5 h-5 mr-2" />
                  Supprimer
                </button>
              )}
              {(['config', 'reconcile'].includes(tab) || isNew) && (
                <button
                  onClick={() => saveKb.mutate(formData)}
                  disabled={saveKb.isLoading}
                  className="flex items-center px-4 py-2 bg-teal-600 text-white rounded-lg hover:bg-teal-700 disabled:opacity-50"
                >
                  <Save className="w-5 h-5 mr-2" />
                  {saveKb.isLoading ? 'Sauvegarde...' : isNew ? 'Créer' : 'Sauvegarder'}
                </button>
              )}
            </div>
          </div>
 
          {isLoading && !isNew ? (
            <div className="flex items-center justify-center h-64">
              <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-teal-600"></div>
            </div>
          ) : (
            <>
              {tab === 'config' && (
                <div className="bg-white rounded-lg shadow p-6 space-y-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">Nom *</label>
                    <input
                      type="text"
                      value={formData.name}
                      onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-teal-500"
                      placeholder="Ex: Ontologie Entreprises"
                      required
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">Description</label>
                    <textarea
                      value={formData.description}
                      onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                      rows={2}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-teal-500"
                    />
                  </div>
                  <div>
                    <div className="flex items-center justify-between mb-1">
                      <label className="block text-sm font-medium text-gray-700">Propriétés de nom</label>
                      <button
                        type="button"
                        onClick={() => setNamePredicates([])}
                        className="text-xs text-teal-700 hover:underline"
                      >
                        Réinitialiser (défaut)
                      </button>
                    </div>
                    <p className="text-xs text-gray-500 mb-2">
                      Propriétés servant à déterminer le nom d'une entité (et le signal d'identité à la
                      réconciliation). Liste par défaut pré-remplie, modifiable.
                    </p>
                    <ul className="space-y-1 mb-2">
                      {effectiveNamePredicates.map((p, i) => (
                        <li
                          key={`${p}-${i}`}
                          className="flex items-center justify-between gap-2 px-2 py-1 rounded border border-gray-200 bg-gray-50"
                        >
                          <span className="font-mono text-xs text-gray-700 truncate">{p}</span>
                          <button
                            type="button"
                            title="Supprimer"
                            onClick={() => removeNamePredicate(p)}
                            className="p-1 text-red-500 hover:bg-red-50 rounded flex-shrink-0"
                          >
                            <Trash2 className="w-3.5 h-3.5" />
                          </button>
                        </li>
                      ))}
                    </ul>
                    <div className="flex gap-2">
                      <input
                        type="text"
                        value={namePredicateInput}
                        onChange={(e) => setNamePredicateInput(e.target.value)}
                        onKeyDown={(e) => {
                          if (e.key === 'Enter') {
                            e.preventDefault();
                            addNamePredicate();
                          }
                        }}
                        placeholder="https://schema.org/name"
                        className="flex-1 px-3 py-2 border border-gray-300 rounded-lg font-mono text-xs focus:ring-2 focus:ring-teal-500"
                      />
                      <button
                        type="button"
                        onClick={addNamePredicate}
                        className="flex items-center px-3 py-2 bg-teal-600 text-white rounded-lg hover:bg-teal-700 text-sm"
                      >
                        <Plus className="w-4 h-4 mr-1" />
                        Ajouter
                      </button>
                    </div>
                    <p className="text-xs text-gray-400 mt-1">
                      {formData.namePredicates?.length
                        ? `${formData.namePredicates.length} personnalisée(s)`
                        : `Liste par défaut (${DEFAULT_NAME_PREDICATES.length})`}
                    </p>
                  </div>
                  {kb?.datasetIri && (
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">Dataset IRI</label>
                      <input
                        type="text"
                        value={kb.datasetIri}
                        readOnly
                        className="w-full px-3 py-2 border border-gray-200 rounded-lg bg-gray-50 text-gray-500 text-sm"
                      />
                    </div>
                  )}
                </div>
              )}
 
              {tab === 'structure' && (
                <SemanticSourcesEditor
                  organizationId={organizationId}
                  disabled={savingSources}
                  value={isNew ? pendingSources : { ontologySources: kb?.ontologies || [], shapesSources: kb?.shapes || [] }}
                  onChange={applySourcesChange}
                  hint="Ontologies OWL et shapes SHACL conservées (MinIO / bibliothèque) et fournies au prompt de raffinage. Les triplets de données référencent les IRIs externes — elles ne sont pas recopiées dans la base."
                />
              )}
 
              {tab === 'explore' && (
                <div className="space-y-4">
                  <div className="flex flex-wrap gap-1">
                    {[
                      { id: 'yasgui', label: 'Console YASGUI' },
                      { id: 'simple', label: 'Console rapide' },
                      { id: 'graph', label: 'Vue graphe' },
                    ].map((m) => (
                      <button
                        key={m.id}
                        type="button"
                        onClick={() => setExploreMode(m.id)}
                        className={`px-3 py-1.5 text-sm rounded-lg border-2 transition-all ${
                          exploreMode === m.id
                            ? 'border-teal-500 bg-teal-50 text-teal-700'
                            : 'border-transparent text-gray-600 hover:bg-gray-50'
                        }`}
                      >
                        {m.label}
                      </button>
                    ))}
                  </div>
 
                  {exploreMode === 'yasgui' && (
                    <div className="bg-white rounded-lg shadow p-4 space-y-3">
                      <p className="text-sm text-gray-500">
                        YASGUI (MIT) — endpoint isolé aux graphs de cette KB ({kb?.stats?.triples ?? 0} triplets) ;{' '}
                        <code>GRAPH/FROM/SERVICE</code> refusés.
                      </p>
                      <YasguiConsole
                        endpoint={`${API_URL}/api/v1/semantic-kbs/${id}/sparql`}
                        token={localStorage.getItem('accessToken')}
                      />
                    </div>
                  )}
 
                  {exploreMode === 'simple' && (
                    <>
                      <div className="bg-white rounded-lg shadow p-6 space-y-3">
                        <div className="flex items-center gap-2">
                          <Database className="w-5 h-5 text-teal-600" />
                          <h3 className="font-medium text-gray-900">Console SPARQL (lecture seule)</h3>
                        </div>
                        <p className="text-sm text-gray-500">
                          Requêtes isolées aux graphs de cette KB ({kb?.stats?.triples ?? 0} triplets).{' '}
                          <code>GRAPH/FROM/SERVICE</code> sont refusés.
                        </p>
                        <textarea
                          value={sparqlQuery}
                          onChange={(e) => setSparqlQuery(e.target.value)}
                          rows={6}
                          className="w-full px-3 py-2 border border-gray-300 rounded-lg font-mono text-sm focus:ring-2 focus:ring-teal-500"
                        />
                        <button
                          onClick={() => runSparql.mutate()}
                          disabled={runSparql.isLoading}
                          className="flex items-center px-4 py-2 bg-teal-600 text-white rounded-lg hover:bg-teal-700 disabled:opacity-50"
                        >
                          <Play className="w-5 h-5 mr-2" />
                          {runSparql.isLoading ? 'Exécution...' : 'Exécuter'}
                        </button>
                      </div>
 
                      {sparqlResult && (
                        <div className="bg-white rounded-lg shadow p-6 overflow-x-auto">
                          {sparqlResult.vars.length === 0 ? (
                            <p className="text-sm text-gray-500">Aucun résultat.</p>
                          ) : (
                            <table className="min-w-full text-sm">
                              <thead>
                                <tr className="border-b">
                                  {sparqlResult.vars.map((v) => (
                                    <th key={v} className="text-left px-3 py-2 font-medium text-gray-700">{v}</th>
                                  ))}
                                </tr>
                              </thead>
                              <tbody>
                                {sparqlResult.rows.map((row, i) => (
                                  <tr key={i} className="border-b hover:bg-gray-50">
                                    {row.map((cell, j) => (
                                      <td key={j} className="px-3 py-2 font-mono text-xs text-gray-800 break-all">{cell}</td>
                                    ))}
                                  </tr>
                                ))}
                              </tbody>
                            </table>
                          )}
                        </div>
                      )}
                    </>
                  )}
 
                  {exploreMode === 'graph' && (
                    <div className="bg-white rounded-lg shadow p-6 space-y-3">
                      <h3 className="font-medium text-gray-900">Vue graphe</h3>
                      <p className="text-sm text-gray-500">
                        Nœuds et liens du graphe. Cliquez un nœud pour l'étendre (voisinage).
                      </p>
                      <SemanticGraphViewer kbId={id} />
                    </div>
                  )}
                </div>
              )}
 
              {tab === 'reconcile' && (
                <div className="space-y-4">
                  <div className="bg-white rounded-lg shadow p-6 space-y-3">
                    <h3 className="font-medium text-gray-900">Politique de fusion</h3>
                    <div className="flex flex-wrap items-center gap-3">
                      <select
                        value={formData.ingestMode}
                        onChange={(e) => setFormData({ ...formData, ingestMode: e.target.value })}
                        className="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-teal-500"
                      >
                        <option value="review">Revue humaine — les fusions sont mises en revue ci-dessous</option>
                        <option value="auto">Automatique — fusion appliquée à l'ingestion</option>
                      </select>
                      <span className="text-xs text-gray-500">Pris en compte au prochain raffinage après « Sauvegarder ».</span>
                    </div>
                    <p className="text-xs text-gray-500">
                      <code>review</code> : les valeurs <strong>mono-valuées divergentes</strong> et les liens
                      proposés sont mis en revue. <code>auto</code> : ils sont <strong>fusionnés automatiquement</strong>
                      (fusion LLM des valeurs, fusion des entités liées).
                    </p>
                  </div>
 
                  <div className="bg-white rounded-lg shadow p-6 space-y-4">
                    <div className="flex flex-wrap items-center justify-between gap-2">
                      <div className="flex items-center gap-2">
                        <AlertTriangle className="w-5 h-5 text-amber-500" />
                        <h3 className="font-medium text-gray-900">Conflits en attente</h3>
                        <span className="px-2 py-0.5 rounded text-xs bg-amber-50 text-amber-700">{conflicts.length}</span>
                      </div>
                      <button
                        onClick={() => reindexKb.mutate()}
                        disabled={reindexKb.isLoading}
                        className="flex items-center px-3 py-1.5 text-sm text-teal-700 border border-teal-300 rounded-lg hover:bg-teal-50 disabled:opacity-50"
                      >
                        <RotateCw className={`w-4 h-4 mr-1.5 ${reindexKb.isLoading ? 'animate-spin' : ''}`} />
                        Réindexer l'index
                      </button>
                    </div>
                    <p className="text-sm text-gray-500">
                      Les prédicats <strong>mono-valués divergents</strong> et les liens d'entités proposés
                      apparaissent ici (en mode <strong>revue</strong>). Les prédicats complémentaires sont
                      ajoutés directement. En mode <code>auto</code>, ces cas sont fusionnés à l'ingestion.
                    </p>
 
                    {conflicts.length === 0 ? (
                      <p className="text-sm text-gray-400">Aucun conflit.</p>
                    ) : (
                      <div className="overflow-x-auto">
                        <table className="min-w-full text-sm">
                          <thead className="bg-gray-50 text-gray-500">
                            <tr>
                              <th className="text-left px-3 py-2 font-medium">Type</th>
                              <th className="text-left px-3 py-2 font-medium">Entité</th>
                              <th className="text-left px-3 py-2 font-medium">Prédicat</th>
                              <th className="text-left px-3 py-2 font-medium">Existant</th>
                              <th className="text-left px-3 py-2 font-medium">Entrant</th>
                              <th className="text-right px-3 py-2 font-medium">Actions</th>
                            </tr>
                          </thead>
                          <tbody>
                            {conflicts.map((c) => (
                              <tr key={c._id} className="border-t border-gray-100">
                                <td className="px-3 py-2">
                                  {c.kind === 'link' ? (
                                    <span className="inline-flex items-center gap-1 text-teal-700">
                                      <Link2 className="w-3.5 h-3.5" /> Lien
                                    </span>
                                  ) : (
                                    <span className="inline-flex items-center gap-1 text-amber-700">
                                      <AlertTriangle className="w-3.5 h-3.5" /> Valeur
                                    </span>
                                  )}
                                </td>
                                <td className="px-3 py-2 font-mono text-xs text-gray-700 break-all max-w-[16rem]">{c.entityIri}</td>
                                <td className="px-3 py-2 text-gray-700">{c.predicateLabel || c.predicate || '—'}</td>
                                <td className="px-3 py-2 text-gray-600 break-all">{(c.existingValues || []).join(', ') || '—'}</td>
                                <td className="px-3 py-2 text-gray-800 break-all">{c.incomingValue}</td>
                                <td className="px-3 py-2">
                                  {(() => {
                                    const rowAction = pending[c._id];
                                    const rowPending = Boolean(rowAction);
                                    return (
                                  <div className="flex items-center justify-end gap-1">
                                    {rowPending && (
                                      <span
                                        title={rowAction === 'merge' ? 'Fusion en cours…' : 'Traitement en cours…'}
                                        className="inline-flex items-center gap-1 text-xs text-teal-700 mr-1"
                                      >
                                        <Loader2 className="w-3.5 h-3.5 animate-spin" />
                                        {rowAction === 'merge' ? 'Fusion…' : '…'}
                                      </span>
                                    )}
                                    <button
                                      title="Rejeter le conflit et ne rien changer aux triplets"
                                      onClick={() => resolveConflict({ conflictId: c._id, action: 'ignore' })}
                                      disabled={rowPending}
                                      className="px-2 py-1 text-xs border border-gray-300 rounded hover:bg-gray-50 disabled:opacity-40 disabled:cursor-not-allowed"
                                    >
                                      Ignorer
                                    </button>
                                    {c.kind === 'value' ? (
                                      <>
                                        <button
                                          title="Remplacer la valeur existante par la valeur entrante"
                                          onClick={() => resolveConflict({ conflictId: c._id, action: 'replace' })}
                                          disabled={rowPending}
                                          className="px-2 py-1 text-xs border border-gray-300 rounded hover:bg-gray-50 disabled:opacity-40 disabled:cursor-not-allowed"
                                        >
                                          Remplacer
                                        </button>
                                        <button
                                          title="Fusionner les deux valeurs en une seule (LLM)"
                                          onClick={() => resolveConflict({ conflictId: c._id, action: 'merge' })}
                                          disabled={rowPending}
                                          className="px-2 py-1 text-xs text-white bg-teal-600 rounded hover:bg-teal-700 disabled:opacity-40 disabled:cursor-not-allowed"
                                        >
                                          {rowAction === 'merge' ? 'Fusionner…' : 'Fusionner'}
                                        </button>
                                      </>
                                    ) : (
                                      <button
                                        title="Fusionner les deux entités (réutiliser l'IRI existante)"
                                        onClick={() => resolveConflict({ conflictId: c._id, action: 'merge' })}
                                        disabled={rowPending}
                                        className="px-2 py-1 text-xs text-white bg-teal-600 rounded hover:bg-teal-700 disabled:opacity-40 disabled:cursor-not-allowed"
                                      >
                                        {rowAction === 'merge' ? 'Fusionner…' : 'Fusionner'}
                                      </button>
                                    )}
                                  </div>
                                    );
                                  })()}
                                </td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                    )}
                  </div>
                </div>
              )}
 
              {tab === 'entities' && (
                <div className="bg-white rounded-lg shadow p-6 space-y-3">
                  <h3 className="font-medium text-gray-900">Recherche d'entités indexées</h3>
                  <p className="text-sm text-gray-500">
                    Recherche vectorielle dans l'index de réconciliation de cette KB (par label).
                  </p>
                    <div className="flex gap-2">
                      <input
                        type="text"
                        value={entityQuery}
                        onChange={(e) => setEntityQuery(e.target.value)}
                        onKeyDown={(e) => { if (e.key === 'Enter') searchEntities.mutate(entityQuery); }}
                        placeholder="Rechercher par label (ex: Coop des Communs)…"
                        className="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-teal-500"
                      />
                      <button
                        onClick={() => searchEntities.mutate(entityQuery)}
                        disabled={searchEntities.isLoading}
                        className="flex items-center px-4 py-2 bg-teal-600 text-white rounded-lg hover:bg-teal-700 disabled:opacity-50"
                      >
                        <Search className="w-4 h-4 mr-1.5" />
                        Rechercher
                      </button>
                    </div>
                    {entities.length > 0 && (
                      <ul className="divide-y divide-gray-100">
                        {entities.map((e) => (
                          <li key={e.iri} className="py-2 flex items-center justify-between gap-3">
                            <div className="min-w-0">
                              <div className="text-sm font-medium text-gray-900 truncate">{e.label || e.iri}</div>
                              <div className="text-xs text-gray-400 font-mono truncate">{e.iri}</div>
                            </div>
                            {e.score !== undefined && (
                              <span className="text-xs text-gray-500 flex-shrink-0">{Number(e.score).toFixed(3)}</span>
                            )}
                          </li>
                        ))}
                      </ul>
                    )}
                </div>
              )}
            </>
          )}
        </div>
      </div>
    </BackofficeEntityPage>
  );
}