#!/bin/bash
# ci-pipeline-logs.sh - Fetch Woodpecker CI pipeline logs
# Usage: ci-pipeline-logs.sh -n <pipeline_num> [-r <repo>] [-s <step>]

set -e

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

# Parse arguments
REPO=""
PIPELINE_NUM=""
STEP=""

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

Fetch logs for a Woodpecker CI pipeline.

Options:
  -n, --number <num>       Pipeline number (required)
  -r, --repo <owner/repo>  Repository (default: auto-detect from git remote)
  -s, --step <step>        Specific step name/number
  -h, --help               Show this help

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

Examples:
  # Get all logs for pipeline 42
  ci-pipeline-logs.sh -n 42

  # Get logs for specific step
  ci-pipeline-logs.sh -n 42 -s test

  # Get logs for specific repo
  ci-pipeline-logs.sh -r mosaic/stack -n 42
EOF
}

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

# Validate required arguments
if [[ -z "$PIPELINE_NUM" ]]; then
    echo "Error: Pipeline number is required (-n)"
    show_help
    exit 1
fi

# 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 logs
if [[ -n "$STEP" ]]; then
    # Get logs for specific step
    woodpecker log show "$REPO" "$PIPELINE_NUM" "$STEP"
else
    # Get all logs
    woodpecker log show "$REPO" "$PIPELINE_NUM"
fi
