#!/bin/bash
# Pre-push hook: Verify CI passes before pushing to remote
# Prevents pushing code that fails local checks

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Telemetry helper function
log_telemetry() {
    local event_type=$1
    local details=$2
    local events_file=".devloop/events.jsonl"

    if [ ! -d ".devloop" ]; then
        return
    fi

    # Create JSONL entry (basic implementation without Python)
    local timestamp=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
    echo "{\"event_type\": \"$event_type\", \"timestamp\": \"$timestamp\", $details}" >> "$events_file"
}

echo -e "${YELLOW}[CI Check] Running pre-push verification...${NC}"

# Try to use devloop's provider-based system first
CI_CHECK_OUTPUT=""
if command -v python3 &> /dev/null; then
    SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
    PRE_PUSH_SCRIPT="$SCRIPT_DIR/../../cli/pre_push_check.py"
    
    if [ -f "$PRE_PUSH_SCRIPT" ]; then
        CI_CHECK_OUTPUT=$(python3 "$PRE_PUSH_SCRIPT" 2>/dev/null)
    fi
fi

# Parse provider output if available
if [ -n "$CI_CHECK_OUTPUT" ]; then
    CI_PROVIDER=$(echo "$CI_CHECK_OUTPUT" | python3 -c "import sys, json; d=json.load(sys.stdin); print(d.get('provider', 'unknown'))" 2>/dev/null || echo "")
    STATUS=$(echo "$CI_CHECK_OUTPUT" | python3 -c "import sys, json; d=json.load(sys.stdin); print(d.get('status', ''))" 2>/dev/null || echo "")
    CONCLUSION=$(echo "$CI_CHECK_OUTPUT" | python3 -c "import sys, json; d=json.load(sys.stdin); print(d.get('conclusion', '') or '')" 2>/dev/null || echo "")
    CI_URL=$(echo "$CI_CHECK_OUTPUT" | python3 -c "import sys, json; d=json.load(sys.stdin); print(d.get('url', ''))" 2>/dev/null || echo "")
    BRANCH=$(echo "$CI_CHECK_OUTPUT" | python3 -c "import sys, json; d=json.load(sys.stdin); print(d.get('branch', ''))" 2>/dev/null || echo "")
fi

# Fall back to GitHub CLI if provider-based check didn't work
if [ -z "$STATUS" ]; then
    # Check if gh CLI is available
    if ! command -v gh &> /dev/null; then
        echo -e "${YELLOW}[CI Check] No CI provider available${NC}"
        exit 0
    fi
    
    # Get the branch being pushed
    BRANCH=$(git rev-parse --abbrev-ref HEAD)
    
    # Check recent CI runs on this branch using gh's built-in --jq (no external jq needed)
    STATUS=$(gh run list --branch "$BRANCH" --limit 1 --json status --jq '.[0].status' 2>/dev/null || echo "")
    CONCLUSION=$(gh run list --branch "$BRANCH" --limit 1 --json conclusion --jq '.[0].conclusion' 2>/dev/null || echo "")
    CI_PROVIDER="GitHub Actions"
fi

echo -e "${YELLOW}[CI Check] Checking CI status for branch: $BRANCH (${CI_PROVIDER})${NC}"

if [ -z "$STATUS" ]; then
    echo -e "${YELLOW}[CI Check] No previous CI runs found${NC}"
    exit 0
fi

# If run is in progress, wait for completion (up to 2 minutes)
if [ "$STATUS" != "completed" ]; then
    echo -e "${YELLOW}[CI Check] Previous CI run in progress, waiting for completion...${NC}"

    WAIT_TIME=0
    MAX_WAIT=120  # 2 minutes
    POLL_INTERVAL=5

    while [ $WAIT_TIME -lt $MAX_WAIT ]; do
        sleep $POLL_INTERVAL
        WAIT_TIME=$((WAIT_TIME + POLL_INTERVAL))

        STATUS=$(gh run list --branch "$BRANCH" --limit 1 --json status --jq '.[0].status' 2>/dev/null || echo "")
        CONCLUSION=$(gh run list --branch "$BRANCH" --limit 1 --json conclusion --jq '.[0].conclusion' 2>/dev/null || echo "")

        if [ "$STATUS" = "completed" ]; then
            echo -e "${YELLOW}[CI Check] CI completed with status: $CONCLUSION${NC}"
            break
        fi

        echo -e "${YELLOW}[CI Check] Still waiting... ($WAIT_TIME/$MAX_WAIT seconds)${NC}"
    done

    # If still not completed, inform user
    if [ "$STATUS" != "completed" ]; then
        echo -e "${YELLOW}[CI Check] CI still running after 2 minutes${NC}"
        echo -e "${YELLOW}[CI Check] You can push and monitor at: https://github.com/$(git config --get remote.origin.url | sed 's/.*github.com[:/]\(.*\)\.git/\1/')/actions${NC}"
        exit 0
    fi
fi

# Check conclusion
if [ "$CONCLUSION" = "failure" ] || [ "$CONCLUSION" = "timed_out" ] || [ "$CONCLUSION" = "cancelled" ]; then
    echo -e "${RED}[CI Check] ❌ Last CI run failed with status: $CONCLUSION${NC}"
    echo -e "${RED}[CI Check] View the failed run: gh run list --branch $BRANCH${NC}"
    echo -e "${RED}[CI Check] Please fix CI issues before pushing${NC}"

    # Log prevented bad push to telemetry
    log_telemetry "pre_push_check" "\"success\": false, \"prevented_bad_push\": true, \"reason\": \"$CONCLUSION\""

    exit 1
fi

if [ "$CONCLUSION" = "success" ]; then
    echo -e "${GREEN}[CI Check] ✅ Latest CI run passed${NC}"

    # Log successful pre-push check to telemetry
    log_telemetry "pre_push_check" "\"success\": true, \"prevented_bad_push\": false"

    # After CI passes, extract DevLoop findings and create Beads issues
    echo -e "${YELLOW}[Findings] Extracting DevLoop findings...${NC}"

    # Find the extract-findings-to-beads script
    SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
    FINDINGS_SCRIPT="$SCRIPT_DIR/../../.agents/hooks/extract-findings-to-beads"

    if [ -x "$FINDINGS_SCRIPT" ]; then
        # Get current git commit hash to link findings
        CURRENT_COMMIT=$(git rev-parse HEAD)

        # Extract findings and create Beads issues
        if "$FINDINGS_SCRIPT"; then
            echo -e "${GREEN}[Findings] ✅ DevLoop findings processed${NC}"
        else
            echo -e "${YELLOW}[Findings] ⚠️  Could not process DevLoop findings (non-blocking)${NC}"
        fi
    else
        echo -e "${YELLOW}[Findings] 📝 Extract-findings script not found (optional)${NC}"
    fi

    exit 0
fi

# For any other status, allow push
echo -e "${YELLOW}[CI Check] Unable to verify CI status (status: $CONCLUSION), allowing push${NC}"
exit 0
