#!/bin/bash

# ====================================================================================
# SCRIPT TO EXPORT GITHUB ISSUES TO A MARKDOWN FILE
# ====================================================================================
set -e # Exit script if a command fails

# --- Default Configuration ---
ISSUE_LIMIT=1000
DEFAULT_LABEL="sred-eligible"
DEFAULT_STATE="open"

# --- Parse Command Line Arguments ---
STATE=""
LABEL=""

# If no arguments are provided, run in legacy SR&ED mode
if [ $# -eq 0 ]; then
    STATE=$DEFAULT_STATE
    LABEL=$DEFAULT_LABEL
else
    while [[ "$#" -gt 0 ]]; do
        case $1 in
            --state=*) STATE="${1#*=}" ;;
            --state) STATE="$2"; shift ;;
            --label=*) LABEL="${1#*=}" ;;
            --label) LABEL="$2"; shift ;;
            *) echo "Unknown parameter passed: $1"; exit 1 ;;
        esac
        shift
    done
fi

# --- Dynamic Configuration ---
STATE_FOR_CMD=${STATE:-"open"} # Default to open if state is empty
LABEL_FOR_FILENAME=${LABEL:-"all"}
STATE_FOR_FILENAME=${STATE:-"open"}

OUTPUT_FILE="export-issues-${STATE_FOR_FILENAME}-${LABEL_FOR_FILENAME}.md"
TITLE="Export of GitHub Issues (State: ${STATE_FOR_FILENAME}, Label: ${LABEL_FOR_FILENAME})"
FETCH_MESSAGE="Fetching issues with state '${STATE_FOR_CMD}'"
if [ -n "$LABEL" ]; then
    FETCH_MESSAGE="${FETCH_MESSAGE} and label '${LABEL}'"
fi

echo "🚀 Starting export of GitHub issues to '${OUTPUT_FILE}'..."

# --- Step 1: Dependency Check ---
echo "1. Checking for 'gh' CLI dependency..."
if ! command -v gh &> /dev/null; then
    echo "❌ ERROR: GitHub CLI ('gh') is not installed. Please install it to continue."
    exit 1
fi
echo "✅ 'gh' CLI found."

# --- Step 2: Initialize Output File ---
echo "# ${TITLE}" > "$OUTPUT_FILE"
echo "" >> "$OUTPUT_FILE"
echo "*Export generated on $(date)*." >> "$OUTPUT_FILE"
echo "" >> "$OUTPUT_FILE"

# --- Step 3: Build 'gh' command and Fetch Issues ---
echo "2. ${FETCH_MESSAGE}..."

GH_COMMAND=("gh" "issue" "list" "--state" "${STATE_FOR_CMD}" "--limit" "$ISSUE_LIMIT" "--json" "number")
if [ -n "$LABEL" ]; then
    GH_COMMAND+=("--label" "${LABEL}")
fi

issue_numbers=$("${GH_COMMAND[@]}" | jq -r '.[].number')

if [ -z "$issue_numbers" ]; then
    echo "⚠️ No issues found matching the criteria."
    echo "" >> "$OUTPUT_FILE"
    echo "**No issues found.**" >> "$OUTPUT_FILE"
    exit 0
fi

total_issues=$(echo "$issue_numbers" | wc -l | xargs)
echo "✅ Found ${total_issues} issue(s)."

# --- Step 4: Loop Through Each Issue and Format the Output ---
echo "3. Formatting details for each issue..."

current_issue=0
for number in $issue_numbers; do
    current_issue=$((current_issue + 1))
    echo "  -> Processing issue #${number} (${current_issue}/${total_issues})"
    
    # Use 'gh issue view' with a template to format the output for each issue
    gh issue view "$number" --json number,title,body,author,createdAt,state --template \
'\n### [#{{.number}}] {{.title}} ({{.state}})\n\n{{if .body}}{{.body}}{{else}}*No description provided.*{{end}}\n\n**Meta:** {{.author.login}} | **Created:** {{timefmt "2006-01-02" .createdAt}}\n***\n' >> "$OUTPUT_FILE"
done

echo ""
echo "🎉 Export complete!"
echo "Your markdown file is ready: ${OUTPUT_FILE}"