#!/usr/bin/env python3
# Copyright (c) 2025-2026 IB-Robot Group & openEuler Embedded SIG & openharmony-robot sig_RoboFrame.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Validate the IBMW commit-message contract."""

from __future__ import annotations

import re
import sys
from pathlib import Path


HEADER = re.compile(
    r"^(feat|fix|docs|test|build|refactor|chore|ci|perf|bench|diag|revert)"
    r"\(([A-Za-z0-9][A-Za-z0-9._/-]*)\): (\S(?:.*\S)?)$"
)
# Case-sensitive prefixes that git (or a forge merge button) generates itself (TOOL-044).
AUTOMATIC = re.compile(
    r"^(Merge (branch|branches|remote-tracking branch|tag|commit|pull request) "
    r"|Revert \"|fixup! |squash! |amend! )"
)
BODY_REQUIRED_TYPES = {"feat", "fix", "refactor", "perf", "bench", "diag", "revert"}
REQUIRED_SECTIONS = ("What:", "Why:", "Verification:")


def fail(message: str) -> int:
    print(f"commit-msg: ERROR: {message}", file=sys.stderr)
    return 1


def main() -> int:
    if len(sys.argv) != 2:
        return fail("usage: commit-msg <message-file>")
    path = Path(sys.argv[1])
    try:
        lines = path.read_text(encoding="utf-8").splitlines()
    except (OSError, UnicodeError) as exc:
        return fail(f"cannot read {path}: {exc}")
    if not lines or not lines[0].strip():
        return fail("the subject is empty")

    subject_line = lines[0]
    if AUTOMATIC.match(subject_line):
        return 0
    match = HEADER.fullmatch(subject_line)
    if not match:
        return fail("subject must match <type>(<scope>): <subject> with an allowed type")
    subject = match.group(3)
    if len(subject) > 72:
        return fail(f"subject text is {len(subject)} characters; maximum is 72")

    commit_type = match.group(1)
    if commit_type in BODY_REQUIRED_TYPES:
        body = "\n".join(lines[1:])
        missing = [section for section in REQUIRED_SECTIONS
                   if not re.search(rf"(?m)^{re.escape(section)}(?:\s|$)", body)]
        if missing:
            return fail("non-trivial commits require body sections: " + ", ".join(missing))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())