# Copyright (C) 2026 GoodData Corporation

"""Commit policy checker shared by CLI and validate tool."""

from __future__ import annotations

from pathlib import Path

from aida_mcp.server.commit_cli import validate_commit_message
from aida_mcp.tools.core.git_policy_config import CommitPolicy, load_git_policy
from aida_mcp.utils.git import list_commit_messages_vs_upstream


def check_commit_policy_range(
    *,
    workspace_root: Path,
    from_ref: str,
    to_ref: str = "HEAD",
    policy: CommitPolicy | None = None,
) -> dict[str, object]:
    active_policy = policy or load_git_policy(workspace_root).commit
    commits = list_commit_messages_vs_upstream(workspace_root, upstream_ref=from_ref, head_ref=to_ref)
    violations: list[dict[str, object]] = []
    for sha, message in commits:
        errors = validate_commit_message(message, policy=active_policy)
        if errors:
            violations.append({"sha": sha, "errors": errors})
    return {
        "checked_commits": len(commits),
        "violations": violations,
        "success": not violations,
        "range": f"{from_ref}..{to_ref}",
    }
