"""
Conflict Detection - Detect and suggest resolutions for proposal conflicts.

Detects when multiple open proposals modify the same fields, which could
lead to merge conflicts if both are approved.
"""

from __future__ import annotations

from typing import Any

from pycharter.wiki.versioning.diff import compute_ontology_diff


def detect_proposal_conflicts(
    proposals: list[dict[str, Any]],
) -> list[dict[str, Any]]:
    """
    Detect fields modified by multiple open proposals.

    Each proposal dict should include:
    - 'id': Proposal ID
    - 'title': Proposal title
    - 'base_content': Common ancestor ontology content
    - 'proposed_content': Proposed ontology content

    Args:
        proposals: List of proposal dicts with base and proposed content

    Returns:
        List of conflict dicts with 'field', 'proposals' keys
    """
    # Track which fields each proposal modifies
    field_to_proposals: dict[str, list[dict[str, str]]] = {}

    for proposal in proposals:
        base = proposal.get("base_content", {})
        proposed = proposal.get("proposed_content", {})
        diff = compute_ontology_diff(base, proposed)

        for change in diff.changes:
            if change.field_name not in field_to_proposals:
                field_to_proposals[change.field_name] = []
            field_to_proposals[change.field_name].append(
                {
                    "proposal_id": proposal.get("id", ""),
                    "proposal_title": proposal.get("title", ""),
                    "change_type": change.change_type.value,
                }
            )

    # Return fields modified by more than one proposal
    conflicts = []
    for field_name, touching_proposals in sorted(field_to_proposals.items()):
        if len(touching_proposals) > 1:
            conflicts.append(
                {
                    "field": field_name,
                    "proposals": touching_proposals,
                }
            )

    return conflicts


def suggest_resolution(conflict: dict[str, Any]) -> str:
    """
    Suggest a resolution strategy for a conflict.

    Args:
        conflict: A conflict dict from detect_proposal_conflicts()

    Returns:
        Human-readable suggestion string
    """
    field = conflict.get("field", "unknown")
    proposals = conflict.get("proposals", [])
    count = len(proposals)

    if count == 2:
        return (
            f"Field '{field}' is modified by 2 proposals. "
            f"Consider merging one first, then rebasing the other."
        )
    return (
        f"Field '{field}' is modified by {count} proposals. "
        f"Coordinate with authors to merge sequentially."
    )
