{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Notice**: The `semantica.kg_qa` module is temporarily unavailable and will be reintroduced in a future release. Any quality assessment examples in this notebook are disabled."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/advanced/04_Conflict_Resolution_Strategies.ipynb)\n",
    "\n",
    "# Conflict Resolution Strategies\n",
    "\n",
    "## Overview\n",
    "\n",
    "Detect conflicts in knowledge graphs, apply multiple resolution strategies, track sources, and maintain audit trails.\n",
    "\n",
    "\n",
    "**Documentation**: [API Reference](https://semantica.readthedocs.io/reference/conflicts/)\n",
    "\n",
    "## Installation\n",
    "\n",
    "Install Semantica from PyPI:\n",
    "\n",
    "```bash\n",
    "pip install semantica\n",
    "# Or with all optional dependencies:\n",
    "pip install semantica[all]\n",
    "```\n",
    "\n",
    "## Workflow: Detect Conflicts → Multiple Resolution Strategies → Track Sources → Audit\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from datetime import datetime\n",
    "import json\n",
    "from semantica.conflicts import ConflictDetector, ConflictResolver, SourceTracker\n",
    "from semantica.conflicts.conflict_resolver import ResolutionStrategy"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 1: Define Entities with Conflicting Data\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "entities = [\n",
    "    {\n",
    "        \"id\": \"e1\",\n",
    "        \"type\": \"Person\",\n",
    "        \"name\": \"John Doe\",\n",
    "        \"age\": 30,\n",
    "        \"location\": \"New York\",\n",
    "        \"source\": \"source1\",\n",
    "        \"confidence\": 0.8,\n",
    "        \"metadata\": {\"timestamp\": datetime(2023, 1, 1)}\n",
    "    },\n",
    "    {\n",
    "        \"id\": \"e1\",\n",
    "        \"type\": \"Person\",\n",
    "        \"name\": \"John Doe\",\n",
    "        \"age\": 32,\n",
    "        \"location\": \"Boston\",\n",
    "        \"source\": \"source2\",\n",
    "        \"confidence\": 0.9,\n",
    "        \"metadata\": {\"timestamp\": datetime(2023, 6, 1)}\n",
    "    },\n",
    "    {\n",
    "        \"id\": \"e2\",\n",
    "        \"type\": \"Organization\",\n",
    "        \"name\": \"Tech Corp\",\n",
    "        \"founded\": 2010,\n",
    "        \"employees\": 100,\n",
    "        \"source\": \"source1\",\n",
    "        \"confidence\": 0.9,\n",
    "        \"metadata\": {\"timestamp\": datetime(2023, 1, 1)}\n",
    "    },\n",
    "    {\n",
    "        \"id\": \"e2\",\n",
    "        \"type\": \"Organization\",\n",
    "        \"name\": \"Tech Corp\",\n",
    "        \"founded\": 2012,\n",
    "        \"employees\": 150,\n",
    "        \"source\": \"source2\",\n",
    "        \"confidence\": 0.7,\n",
    "        \"metadata\": {\"timestamp\": datetime(2023, 3, 1)}\n",
    "    }\n",
    "]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 2: Detect Conflicts\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Initialize detector\n",
    "detector = ConflictDetector(track_provenance=True)\n",
    "\n",
    "# Detect conflicts across all properties\n",
    "conflicts = detector.detect_entity_conflicts(entities)\n",
    "\n",
    "print(f\"Detected {len(conflicts)} conflicts:\")\n",
    "for i, conflict in enumerate(conflicts, 1):\n",
    "    print(f\"\\nConflict {i}:\")\n",
    "    print(f\"  ID: {conflict.conflict_id}\")\n",
    "    print(f\"  Type: {conflict.conflict_type.value}\")\n",
    "    print(f\"  Entity: {conflict.entity_id}\")\n",
    "    print(f\"  Property: {conflict.property_name}\")\n",
    "    print(f\"  Values: {conflict.conflicting_values}\")\n",
    "    print(f\"  Severity: {conflict.severity}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 3: Resolve Conflicts\n",
    "\n",
    "We can apply different strategies to resolve the conflicts:\n",
    "- **Voting**: Selects the most frequent value\n",
    "- **Most Recent**: Selects the value with the latest timestamp\n",
    "- **Highest Confidence**: Selects the value from the source with highest confidence\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Initialize resolver\n",
    "resolver = ConflictResolver()\n",
    "\n",
    "# Strategy 1: Voting\n",
    "print(\"--- Strategy: Voting ---\")\n",
    "results_voting = resolver.resolve_conflicts(conflicts, strategy=\"voting\")\n",
    "for r in results_voting:\n",
    "    if r.resolved:\n",
    "        print(f\"Resolved {r.conflict_id}: {r.resolved_value} (Confidence: {r.confidence:.2f})\")\n",
    "\n",
    "# Strategy 2: Most Recent\n",
    "print(\"\\n--- Strategy: Most Recent ---\")\n",
    "results_recent = resolver.resolve_conflicts(conflicts, strategy=\"most_recent\")\n",
    "for r in results_recent:\n",
    "    if r.resolved:\n",
    "        print(f\"Resolved {r.conflict_id}: {r.resolved_value}\")\n",
    "\n",
    "# Strategy 3: Highest Confidence\n",
    "print(\"\\n--- Strategy: Highest Confidence ---\")\n",
    "results_confidence = resolver.resolve_conflicts(conflicts, strategy=\"highest_confidence\")\n",
    "for r in results_confidence:\n",
    "    if r.resolved:\n",
    "        print(f\"Resolved {r.conflict_id}: {r.resolved_value} (Confidence: {r.confidence:.2f})\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 4: Track Sources\n",
    "\n",
    "The `ConflictDetector` tracks source provenance when `track_provenance=True`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "tracker = detector.source_tracker\n",
    "\n",
    "for conflict in conflicts:\n",
    "    print(f\"\\nConflict: {conflict.conflict_id}\")\n",
    "    # Get detailed source info for the property\n",
    "    sources = tracker.get_property_sources(conflict.entity_id, conflict.property_name)\n",
    "    if sources:\n",
    "        print(f\"  Entity: {conflict.entity_id}, Property: {conflict.property_name}\")\n",
    "        print(f\"  Sources found: {len(sources.sources)}\")\n",
    "        for src in sources.sources:\n",
    "            print(f\"    - {src.document} (Confidence: {src.confidence})\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 5: Audit Trail\n",
    "\n",
    "The `ConflictResolver` maintains a history of all resolutions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "history = resolver.get_resolution_history()\n",
    "\n",
    "print(f\"Resolution History ({len(history)} entries):\")\n",
    "for entry in history:\n",
    "    print(f\"\\nConflict: {entry.conflict_id}\")\n",
    "    print(f\"  Strategy: {entry.resolution_strategy}\")\n",
    "    print(f\"  Resolved Value: {entry.resolved_value}\")\n",
    "    print(f\"  Notes: {entry.resolution_notes}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Summary\n",
    "\n",
    "Conflict resolution workflow:\n",
    "- Conflict Detection using `ConflictDetector`\n",
    "- Multiple Resolution Strategies (Voting, Most Recent, Highest Confidence)\n",
    "- Source Tracking with `SourceTracker`\n",
    "- Complete Audit Trail via `ConflictResolver`"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}