#!/usr/bin/env bash
set -euo pipefail

# Enforce Conventional Commits format:
#   type(scope): description
#   type: description
#
# Allowed types: feat, fix, docs, style, refactor, perf, test, build, ci, chore, revert
# Scope is optional. Description must be lowercase, no period at end.
# Max subject line: 72 characters.

commit_msg_file="$1"
commit_msg=$(head -1 "$commit_msg_file")

# Allow merge commits
if echo "$commit_msg" | grep -qE "^Merge "; then
    exit 0
fi

# Conventional commit pattern
pattern="^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(\([a-z0-9_-]+\))?(!)?: .{1,}"

if ! echo "$commit_msg" | grep -qE "$pattern"; then
    echo "ERROR: Commit message does not follow Conventional Commits format."
    echo ""
    echo "Expected: type(scope): description"
    echo ""
    echo "Types: feat, fix, docs, style, refactor, perf, test, build, ci, chore, revert"
    echo "Scope: optional, lowercase (e.g., scorer, metadata, cli)"
    echo ""
    echo "Examples:"
    echo "  feat(extractors): add Mastodon extractor"
    echo "  fix(scorer): correct link density calculation"
    echo "  docs: update README installation section"
    echo "  refactor!: simplify retry pipeline"
    echo "  test: add benchmark for large pages"
    echo ""
    echo "Your message: $commit_msg"
    exit 1
fi

# Check subject line length (72 chars max)
if [ ${#commit_msg} -gt 72 ]; then
    echo "ERROR: Subject line is ${#commit_msg} chars (max 72)."
    echo "Your message: $commit_msg"
    exit 1
fi

# Check description starts lowercase (after the colon+space)
desc=$(echo "$commit_msg" | sed 's/^[^:]*: //')
first_char=$(echo "$desc" | cut -c1)
if echo "$first_char" | grep -qE "^[A-Z]$"; then
    echo "ERROR: Description should start lowercase."
    echo "Your message: $commit_msg"
    exit 1
fi

# Check no trailing period
if echo "$commit_msg" | grep -qE '\.$'; then
    echo "ERROR: Subject line should not end with a period."
    echo "Your message: $commit_msg"
    exit 1
fi
