#!/usr/bin/env bash
# lint-relative-paths - Wrapper script for TypeScript linter
#
# This script validates markdown links use repo-relative paths (starting with /)
# Implementation: TypeScript with Bun runtime
#
# Exit codes:
#   0 - Success (no violations or skip condition met)
#   1 - Violations found (lint failure)
#   2 - Hard block / fatal error (Claude Code hook protocol)

set -euo pipefail

WORKSPACE="${1:-$HOME/.claude}"

# Check for marketplace repo markers FIRST (before any output)
if [[ -f "$WORKSPACE/plugin.json" ]] || [[ -f "$WORKSPACE/.claude-plugin" ]]; then
    echo "✅ Marketplace repo detected at: $WORKSPACE"
    echo "   Relative paths (./  ../) are CORRECT for marketplace plugins."
    exit 0
fi

# Check for global ignore file with pattern matching
GLOBAL_IGNORE="$HOME/.claude/lint-relative-paths-ignore"
if [[ -f "$GLOBAL_IGNORE" ]]; then
    while IFS= read -r pattern || [[ -n "$pattern" ]]; do
        # Skip empty lines and comments
        [[ -z "$pattern" || "$pattern" == \#* ]] && continue
        # Check if workspace path contains the pattern
        if [[ "$WORKSPACE" == *"$pattern"* ]]; then
            echo "✅ Workspace matches global ignore pattern: $pattern"
            echo "   Skipping: $WORKSPACE"
            exit 0
        fi
    done < "$GLOBAL_IGNORE"
fi

# Check for explicit skip marker (for repos with third-party content using relative paths)
if [[ -f "$WORKSPACE/.lint-skip-relative-paths" ]]; then
    skip_reason=$(head -1 "$WORKSPACE/.lint-skip-relative-paths" 2>/dev/null || echo "Skip marker present")
    echo "✅ Lint skip marker found at: $WORKSPACE"
    echo "   Reason: $skip_reason"
    exit 0
fi

# Resolve script directory and TypeScript implementation
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BUN_SCRIPT="${SCRIPT_DIR}/lint-relative-paths.ts"

# Bun is REQUIRED - no Python fallback
if ! command -v bun &>/dev/null; then
    echo "❌ [lint-relative-paths] FATAL: Bun is required but not installed" >&2
    echo "   Install with: curl -fsSL https://bun.sh/install | bash" >&2
    echo "   Or: brew install oven-sh/bun/bun" >&2
    exit 2  # Hard block for Claude Code
fi

if [[ ! -f "$BUN_SCRIPT" ]]; then
    echo "❌ [lint-relative-paths] FATAL: TypeScript implementation not found: $BUN_SCRIPT" >&2
    exit 2  # Hard block for Claude Code
fi

# Execute TypeScript implementation with Bun
exec bun run "$BUN_SCRIPT" "$WORKSPACE"
