"""Deduplicate identical tool schemas across multiple agents."""
from __future__ import annotations

import hashlib
import json


def _schema_fingerprint(schema: dict) -> str:
    """Create a stable hash of a tool schema for dedup comparison."""
    canonical = json.dumps(schema, sort_keys=True, separators=(",", ":"))
    return hashlib.md5(canonical.encode()).hexdigest()


def deduplicate_tool_schemas(
    schemas: list[dict] | None,
) -> list[dict] | None:
    """Remove duplicate tool schemas, preserving first-seen order.

    Two schemas are considered duplicates when their full JSON
    representation is identical (compared via MD5 hash).
    """
    if schemas is None:
        return None
    seen: set[str] = set()
    unique: list[dict] = []
    for schema in schemas:
        fp = _schema_fingerprint(schema)
        if fp not in seen:
            seen.add(fp)
            unique.append(schema)
    return unique
