"""System prompt deduplication for multi-agent crews."""
from __future__ import annotations


def extract_common_prefix(prompts: list[str]) -> str:
    """Find the longest common sentence-aligned prefix among prompts.

    Returns the common prefix truncated to the last complete sentence
    (ending with '.', '!', '?', or newline).
    """
    if not prompts:
        return ""
    if len(prompts) == 1:
        return prompts[0]

    prefix = prompts[0]
    for p in prompts[1:]:
        i = 0
        while i < len(prefix) and i < len(p) and prefix[i] == p[i]:
            i += 1
        prefix = prefix[:i]

    if not prefix:
        return ""

    for i in range(len(prefix) - 1, -1, -1):
        if prefix[i] in ".!?\n":
            return prefix[: i + 1].rstrip()
    return ""


def deduplicate_system_prompts(
    prompts: dict[str, str],
    *,
    min_prefix_len: int = 20,
) -> dict:
    """Extract shared prefix from agent system prompts.

    Args:
        prompts: Mapping of agent_name -> system_prompt.
        min_prefix_len: Minimum prefix length to bother deduplicating.

    Returns:
        {"shared_prefix": str, "deltas": {agent_name: str}}
    """
    if not prompts:
        return {"shared_prefix": "", "deltas": {}}

    all_prompts = list(prompts.values())
    prefix = extract_common_prefix(all_prompts)

    if len(prefix) < min_prefix_len:
        return {"shared_prefix": "", "deltas": dict(prompts)}

    deltas = {}
    for name, prompt in prompts.items():
        delta = prompt[len(prefix) :].lstrip()
        deltas[name] = delta

    return {"shared_prefix": prefix, "deltas": deltas}
