"""
Ontology Diff - Field-level comparison between ontology versions.

Operates on raw dicts (the JSONB content), not DB models,
keeping diff logic pure and testable without a database.
"""

from __future__ import annotations

from typing import Any

from pycharter.wiki.versioning.models import FieldChange, FieldChangeType, OntologyDiff


def compute_ontology_diff(
    old_content: dict[str, Any], new_content: dict[str, Any] | None
) -> OntologyDiff:
    """
    Compute field-level diff between two ontology versions.

    Compares the 'fields' dict in each content and detects
    additions, removals, and modifications.

    Args:
        old_content: Previous ontology content dict
        new_content: New ontology content dict

    Returns:
        OntologyDiff with all detected changes
    """
    old_fields = old_content.get("fields", {})
    new_fields = new_content.get("fields", {})

    changes = []

    old_keys = set(old_fields.keys())
    new_keys = set(new_fields.keys())

    # Added fields
    for key in sorted(new_keys - old_keys):
        changes.append(
            FieldChange(
                field_name=key,
                change_type=FieldChangeType.ADDED,
                old_value=None,
                new_value=new_fields[key],
            )
        )

    # Removed fields
    for key in sorted(old_keys - new_keys):
        changes.append(
            FieldChange(
                field_name=key,
                change_type=FieldChangeType.REMOVED,
                old_value=old_fields[key],
                new_value=None,
            )
        )

    # Modified fields
    for key in sorted(old_keys & new_keys):
        if old_fields[key] != new_fields[key]:
            changes.append(
                FieldChange(
                    field_name=key,
                    change_type=FieldChangeType.MODIFIED,
                    old_value=old_fields[key],
                    new_value=new_fields[key],
                )
            )

    return OntologyDiff(changes=changes)
