#!/bin/bash
# ci-pipeline-status.sh - Check Woodpecker CI pipeline status
# Usage: ci-pipeline-status.sh [-r <repo>] [-n <pipeline_num>] [--latest]

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/detect-platform.sh"

# Parse arguments
REPO=""
PIPELINE_NUM=""
LATEST=false

show_help() {
    cat << EOF
Usage: ci-pipeline-status.sh [OPTIONS]

Check Woodpecker CI pipeline status for a repository.

Options:
  -r, --repo <owner/repo>  Repository (default: auto-detect from git remote)
  -n, --number <num>       Pipeline number
  --latest                 Get status of latest pipeline
  -h, --help               Show this help

Environment:
  WOODPECKER_SERVER        Woodpecker server URL (required)
  WOODPECKER_TOKEN         Woodpecker API token (required)

Examples:
  # Get latest pipeline status for current repo
  ci-pipeline-status.sh --latest

  # Get specific pipeline status
  ci-pipeline-status.sh -n 42

  # Get pipeline status for specific repo
  ci-pipeline-status.sh -r mosaic/stack --latest
EOF
}

while [[ $# -gt 0 ]]; do
    case $1 in
        -r|--repo)
            REPO="$2"
            shift 2
            ;;
        -n|--number)
            PIPELINE_NUM="$2"
            shift 2
            ;;
        --latest)
            LATEST=true
            shift
            ;;
        -h|--help)
            show_help
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            show_help
            exit 1
            ;;
    esac
done

# Check required environment variables
if [[ -z "$WOODPECKER_SERVER" ]]; then
    echo "Error: WOODPECKER_SERVER environment variable not set"
    exit 1
fi

if [[ -z "$WOODPECKER_TOKEN" ]]; then
    echo "Error: WOODPECKER_TOKEN environment variable not set"
    exit 1
fi

# Auto-detect repo if not provided
if [[ -z "$REPO" ]]; then
    REPO=$(get_repo_info)
    if [[ $? -ne 0 ]]; then
        echo "Error: Could not auto-detect repository. Use -r option."
        exit 1
    fi
fi

# Check if woodpecker CLI is installed
if ! command -v woodpecker &> /dev/null; then
    echo "Error: woodpecker CLI not found. Install it first:"
    echo "  Arch: paru -S woodpecker"
    echo "  Other: https://woodpecker-ci.org/docs/usage/cli"
    exit 1
fi

# Get pipeline status
if [[ "$LATEST" == true ]]; then
    # Get latest pipeline
    woodpecker pipeline ls "$REPO" --limit 1
elif [[ -n "$PIPELINE_NUM" ]]; then
    # Get specific pipeline info
    woodpecker pipeline info "$REPO" "$PIPELINE_NUM"
else
    echo "Error: Either --latest or -n <number> is required"
    show_help
    exit 1
fi
