#!/usr/bin/env py
"""
Pre-Push Hook: Tag Validation
Stellt sicher dass:
- Nur semver Tags (X.Y.Z) gepusht werden
"""
import sys
import re


def main() -> int:
    """Main pre-push validation"""
    # Tag validation: Enforce semver-only tags (X.Y.Z without 'v' prefix or suffixes)
    semver_re = re.compile(r"^\d+\.\d+\.\d+$")

    # Git provides pushed refs via stdin during an actual push. When the hook
    # is executed interactively (developer running the script directly),
    # `sys.stdin.read()` blocks waiting for EOF. Detect interactive runs and
    # skip reading stdin to avoid hanging locally.
    try:
        if sys.stdin.isatty():
            pushed_lines = []
        else:
            pushed_lines = sys.stdin.read().splitlines()
    except Exception:
        pushed_lines = []

    violating = []
    for line in pushed_lines:
        parts = line.strip().split()
        if len(parts) < 4:
            continue
        local_ref, local_sha, remote_ref, remote_sha = parts
        if remote_ref.startswith("refs/tags/"):
            tag = remote_ref.split("/", 2)[-1]
            # allow tag deletions (local sha all zeros)
            if local_sha == '0000000000000000000000000000000000000000':
                continue
            if not semver_re.match(tag):
                violating.append(tag)

    if violating:
        print("ERROR: Non-semver tags detected:", ", ".join(violating))
        print("Allowed tag pattern: X.Y.Z (e.g., 1.2.3). Push aborted.")
        return 1

    print("✅ Pre-Push Tag Validation Passed")
    return 0


if __name__ == "__main__":
    try:
        sys.exit(main())
    except KeyboardInterrupt:
        print("\n⚠️  Pre-Push validation interrupted")
        sys.exit(1)
    except Exception as e:
        print(f"❌ Pre-Push Hook Error: {e}")
        sys.exit(1)
