#!/usr/bin/env bash
# =============================================================================
# gitlab-release.sh — GitLab release CLI for zexc
# =============================================================================
# Runs quality gates (cargo check, cargo clippy, cargo audit, cargo test),
# builds a release tarball, tags the repo, and publishes a GitLab release
# with the tarball + sha256 attached as release assets.
#
# Usage:
#   ./scripts/gitlab-release.sh [OPTIONS]
#
# Options:
#   --skip-check       Skip cargo check
#   --skip-clippy       Skip cargo clippy
#   --skip-audit       Skip cargo audit
#   --skip-test        Skip cargo test
#   --skip-build       Skip release build (use existing tarball)
#   --skip-all-checks  Skip all quality gates (check, clippy, audit, test)
#   --dry-run          Do everything except push tag / create GitLab release
#   --tag TAG          Override version tag (default: v<Cargo.toml version>)
#   --token TOKEN      GitLab personal access token (or set GITLAB_TOKEN env)
#   --notes "..."      Custom release notes (default: auto-generated)
#   -h, --help         Show this help
#
# Environment:
#   GITLAB_TOKEN       Personal access token with api scope
#   GITLAB_PROJECT_ID  Project ID (auto-detected from remote if not set)
#   GITLAB_API_URL     GitLab API base (default: https://gitlab.com/api/v4)
#
# Requirements:
#   - cargo, rustc
#   - cargo-audit (install: cargo install cargo-audit)
#   - curl, jq, git
#   - python3 (for make configure)
# =============================================================================

set -euo pipefail

# ── Colors ───────────────────────────────────────────────────────────────────
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
BOLD='\033[1m'
DIM='\033[2m'
RESET='\033[0m'

# ── Logging ──────────────────────────────────────────────────────────────────
info()    { printf "${BLUE}[ℹ]${RESET} %s\n" "$*"; }
success() { printf "${GREEN}[✔]${RESET} %s\n" "$*"; }
warn()    { printf "${YELLOW}[⚠]${RESET} %s\n" "$*"; }
error()   { printf "${RED}[✖]${RESET} %s\n" "$*" >&2; }
step()    { printf "\n${BOLD}${CYAN}━━━ %s ━━━${RESET}\n" "$*"; }
substep() { printf "${DIM}    → %s${RESET}\n" "$*"; }

die() { error "$@"; exit 1; }

# ── Defaults ─────────────────────────────────────────────────────────────────
SKIP_CHECK=false
SKIP_CLIPPY=false
SKIP_AUDIT=false
SKIP_TEST=false
SKIP_BUILD=false
DRY_RUN=false
CUSTOM_TAG=""
CUSTOM_NOTES=""
GITLAB_TOKEN="${GITLAB_TOKEN:-}"
GITLAB_PROJECT_ID="${GITLAB_PROJECT_ID:-}"
GITLAB_API_URL="${GITLAB_API_URL:-https://gitlab.com/api/v4}"

# ── Parse args ───────────────────────────────────────────────────────────────
while [[ $# -gt 0 ]]; do
    case "$1" in
        --skip-check)       SKIP_CHECK=true ;;
        --skip-clippy)      SKIP_CLIPPY=true ;;
        --skip-audit)       SKIP_AUDIT=true ;;
        --skip-test)        SKIP_TEST=true ;;
        --skip-build)       SKIP_BUILD=true ;;
        --skip-all-checks)  SKIP_CHECK=true; SKIP_CLIPPY=true; SKIP_AUDIT=true; SKIP_TEST=true ;;
        --dry-run)          DRY_RUN=true ;;
        --tag)              CUSTOM_TAG="$2"; shift ;;
        --token)            GITLAB_TOKEN="$2"; shift ;;
        --notes)            CUSTOM_NOTES="$2"; shift ;;
        -h|--help)
            sed -n '2,/^# ====.*====$/p' "$0" | sed 's/^# \?//'
            exit 0
            ;;
        *)
            die "Unknown option: $1 (use --help)"
            ;;
    esac
    shift
done

# ── Change to project root ──────────────────────────────────────────────────
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
cd "$PROJECT_ROOT"

info "Project root: $PROJECT_ROOT"

# ── Extract metadata ────────────────────────────────────────────────────────
VERSION="$(grep '^version' Cargo.toml | head -1 | cut -d'"' -f2)"
PKG_NAME="$(grep '^name' Cargo.toml | head -1 | cut -d'"' -f2)"
TARGET="$(rustc -vV | sed -n 's/^host: //p')"
TAG="${CUSTOM_TAG:-v${VERSION}}"
TARBALL_NAME="${PKG_NAME}-${VERSION}-${TARGET}.tar.gz"
SHA256_NAME="${TARBALL_NAME}.sha256"

step "zexc GitLab Release Pipeline"
echo ""
printf "  ${BOLD}Package${RESET}    : %s\n" "$PKG_NAME"
printf "  ${BOLD}Version${RESET}    : %s\n" "$VERSION"
printf "  ${BOLD}Tag${RESET}        : %s\n" "$TAG"
printf "  ${BOLD}Target${RESET}     : %s\n" "$TARGET"
printf "  ${BOLD}Tarball${RESET}    : dist/%s\n" "$TARBALL_NAME"
if $DRY_RUN; then
    printf "  ${YELLOW}${BOLD}Mode${RESET}       : ${YELLOW}DRY RUN${RESET}\n"
fi
echo ""

# ── Preflight checks ────────────────────────────────────────────────────────
step "Preflight Checks"

command -v cargo >/dev/null || die "cargo not found"
substep "cargo $(cargo --version 2>/dev/null | head -1)"

command -v rustc >/dev/null || die "rustc not found"
substep "rustc $(rustc --version 2>/dev/null)"

command -v git >/dev/null || die "git not found"
substep "git $(git --version 2>/dev/null)"

command -v curl >/dev/null || die "curl not found — needed for GitLab API"
command -v jq >/dev/null || die "jq not found — install with: sudo pacman -S jq"

if ! $SKIP_AUDIT; then
    if ! command -v cargo-audit >/dev/null 2>&1; then
        warn "cargo-audit not found — install with: cargo install cargo-audit"
        warn "Skipping audit step"
        SKIP_AUDIT=true
    else
        substep "cargo-audit $(cargo audit --version 2>/dev/null)"
    fi
fi

# Check for uncommitted changes
if [[ -n "$(git status --porcelain 2>/dev/null)" ]]; then
    warn "Working tree has uncommitted changes!"
    git status --short
    echo ""
    read -rp "$(printf "${YELLOW}Continue anyway? [y/N]:${RESET} ")" yn
    case "$yn" in
        [Yy]*) ;;
        *) die "Aborted — commit or stash your changes first" ;;
    esac
fi

# Check if tag already exists
if git rev-parse "$TAG" >/dev/null 2>&1; then
    warn "Tag '$TAG' already exists locally"
    read -rp "$(printf "${YELLOW}Delete and re-create? [y/N]:${RESET} ")" yn
    case "$yn" in
        [Yy]*) git tag -d "$TAG" ;;
        *) die "Aborted — choose a different tag with --tag" ;;
    esac
fi

success "Preflight OK"

# ── Gate 1: cargo check ─────────────────────────────────────────────────────
GATE_PASSED=0
GATE_TOTAL=0

if ! $SKIP_CHECK; then
    step "Gate 1 — cargo check"
    GATE_TOTAL=$((GATE_TOTAL + 1))
    if cargo check --all-targets 2>&1; then
        success "cargo check passed"
        GATE_PASSED=$((GATE_PASSED + 1))
    else
        error "cargo check FAILED"
        die "Fix compilation errors before releasing"
    fi
else
    info "Skipping cargo check (--skip-check)"
fi

# ── Gate 2: cargo clippy ────────────────────────────────────────────────────
if ! $SKIP_CLIPPY; then
    step "Gate 2 — cargo clippy"
    GATE_TOTAL=$((GATE_TOTAL + 1))
    if cargo clippy --all-targets -- -D warnings 2>&1; then
        success "cargo clippy passed (no warnings)"
        GATE_PASSED=$((GATE_PASSED + 1))
    else
        warn "cargo clippy found warnings (non-blocking)"
        GATE_PASSED=$((GATE_PASSED + 1))
    fi
else
    info "Skipping cargo clippy (--skip-clippy)"
fi

# ── Gate 3: cargo audit ─────────────────────────────────────────────────────
if ! $SKIP_AUDIT; then
    step "Gate 3 — cargo audit"
    GATE_TOTAL=$((GATE_TOTAL + 1))
    if cargo audit 2>&1; then
        success "cargo audit passed — no known vulnerabilities"
        GATE_PASSED=$((GATE_PASSED + 1))
    else
        warn "cargo audit found advisories"
        read -rp "$(printf "${YELLOW}Continue despite audit warnings? [y/N]:${RESET} ")" yn
        case "$yn" in
            [Yy]*) GATE_PASSED=$((GATE_PASSED + 1)) ;;
            *) die "Aborted — fix vulnerabilities first" ;;
        esac
    fi
else
    info "Skipping cargo audit (--skip-audit)"
fi

# ── Gate 4: cargo test ──────────────────────────────────────────────────────
if ! $SKIP_TEST; then
    step "Gate 4 — cargo test"
    GATE_TOTAL=$((GATE_TOTAL + 1))
    if cargo test --all-targets 2>&1; then
        success "All tests passed"
        GATE_PASSED=$((GATE_PASSED + 1))
    else
        error "Tests FAILED"
        die "Fix failing tests before releasing"
    fi
else
    info "Skipping cargo test (--skip-test)"
fi

# ── Summary of gates ────────────────────────────────────────────────────────
if [[ $GATE_TOTAL -gt 0 ]]; then
    echo ""
    if [[ $GATE_PASSED -eq $GATE_TOTAL ]]; then
        success "Quality gates: ${GATE_PASSED}/${GATE_TOTAL} passed ✓"
    else
        warn "Quality gates: ${GATE_PASSED}/${GATE_TOTAL} passed"
    fi
fi

# ── Build release tarball ────────────────────────────────────────────────────
if ! $SKIP_BUILD; then
    step "Building Release Tarball"
    make release-tarball
    success "Tarball: dist/${TARBALL_NAME}"
    substep "SHA256: dist/${SHA256_NAME}"
else
    info "Skipping build (--skip-build)"
    if [[ ! -f "dist/${TARBALL_NAME}" ]]; then
        die "Tarball not found at dist/${TARBALL_NAME} — remove --skip-build"
    fi
fi

# Verify tarball exists
[[ -f "dist/${TARBALL_NAME}" ]] || die "Tarball not found: dist/${TARBALL_NAME}"
[[ -f "dist/${SHA256_NAME}" ]] || die "SHA256 not found: dist/${SHA256_NAME}"

TARBALL_SIZE="$(du -h "dist/${TARBALL_NAME}" | cut -f1)"
TARBALL_SHA="$(cat "dist/${SHA256_NAME}" | awk '{print $1}')"
substep "Size: ${TARBALL_SIZE}"
substep "SHA256: ${TARBALL_SHA}"

# ── Resolve GitLab project ──────────────────────────────────────────────────
step "GitLab Configuration"

# Auto-detect project path from git remote
REMOTE_URL="$(git remote get-url origin 2>/dev/null || echo "")"
if [[ -z "$REMOTE_URL" ]]; then
    die "No git remote 'origin' found"
fi

# Extract namespace/project from URL
# Handles: https://gitlab.com/user/project.git
#           git@gitlab.com:user/project.git
PROJECT_PATH=""
if [[ "$REMOTE_URL" =~ gitlab\.com[:/](.+)\.git$ ]]; then
    PROJECT_PATH="${BASH_REMATCH[1]}"
elif [[ "$REMOTE_URL" =~ gitlab\.com[:/](.+)$ ]]; then
    PROJECT_PATH="${BASH_REMATCH[1]}"
fi

if [[ -z "$PROJECT_PATH" ]]; then
    die "Could not parse GitLab project path from remote: $REMOTE_URL"
fi

substep "Project path: $PROJECT_PATH"

# URL-encode the project path for API calls
PROJECT_PATH_ENCODED="$(printf '%s' "$PROJECT_PATH" | sed 's|/|%2F|g')"

# Auto-detect project ID if not set
if [[ -z "$GITLAB_PROJECT_ID" ]]; then
    substep "Auto-detecting project ID..."
    if [[ -n "$GITLAB_TOKEN" ]]; then
        PROJECT_ID_RESP="$(curl -sf --header "PRIVATE-TOKEN: ${GITLAB_TOKEN}" \
            "${GITLAB_API_URL}/projects/${PROJECT_PATH_ENCODED}" 2>/dev/null || echo "")"
        if [[ -n "$PROJECT_ID_RESP" ]]; then
            GITLAB_PROJECT_ID="$(echo "$PROJECT_ID_RESP" | jq -r '.id // empty')"
        fi
    fi
    if [[ -z "$GITLAB_PROJECT_ID" ]]; then
        warn "Could not auto-detect project ID"
        read -rp "$(printf "${CYAN}Enter GitLab Project ID:${RESET} ")" GITLAB_PROJECT_ID
        [[ -n "$GITLAB_PROJECT_ID" ]] || die "Project ID is required"
    fi
fi

substep "Project ID: $GITLAB_PROJECT_ID"

# ── Validate token ──────────────────────────────────────────────────────────
if [[ -z "$GITLAB_TOKEN" ]]; then
    echo ""
    warn "GITLAB_TOKEN not set"
    echo "  Create one at: https://gitlab.com/-/user_settings/personal_access_tokens"
    echo "  Required scopes: api"
    echo ""
    read -rsp "$(printf "${CYAN}Enter GitLab token:${RESET} ")" GITLAB_TOKEN
    echo ""
    [[ -n "$GITLAB_TOKEN" ]] || die "Token is required"
fi

# Quick token validation
TOKEN_CHECK="$(curl -sf --header "PRIVATE-TOKEN: ${GITLAB_TOKEN}" \
    "${GITLAB_API_URL}/user" 2>/dev/null || echo "")"
if [[ -z "$TOKEN_CHECK" ]] || echo "$TOKEN_CHECK" | jq -e '.message' >/dev/null 2>&1; then
    die "GitLab token is invalid or expired"
fi
TOKEN_USER="$(echo "$TOKEN_CHECK" | jq -r '.username // "unknown"')"
success "Authenticated as: @${TOKEN_USER}"

# ── Generate release notes ──────────────────────────────────────────────────
step "Release Notes"

if [[ -n "$CUSTOM_NOTES" ]]; then
    RELEASE_NOTES="$CUSTOM_NOTES"
else
    # Auto-generate from git log since last tag
    LAST_TAG="$(git describe --tags --abbrev=0 2>/dev/null || echo "")"
    if [[ -n "$LAST_TAG" ]]; then
        COMMIT_LOG="$(git log "${LAST_TAG}..HEAD" --oneline --no-merges 2>/dev/null || echo "")"
    else
        COMMIT_LOG="$(git log --oneline --no-merges -20 2>/dev/null || echo "")"
    fi

    RELEASE_NOTES="## zexc ${TAG}

### Release Info
- **Version**: ${VERSION}
- **Target**: ${TARGET}
- **SHA256**: \`${TARBALL_SHA}\`

### Changes
$(echo "$COMMIT_LOG" | sed 's/^/- /')

### Installation

\`\`\`bash
# Extract
tar xzf ${TARBALL_NAME}

# Install CLI
sudo install -m 755 zexc-${VERSION}-${TARGET}/zexc /usr/local/bin/

# Install libraries (optional)
sudo install -m 644 zexc-${VERSION}-${TARGET}/libzexc.so /usr/local/lib/
sudo install -m 644 zexc-${VERSION}-${TARGET}/libzexc.a /usr/local/lib/
sudo install -m 644 zexc-${VERSION}-${TARGET}/include/zexc.h /usr/local/include/
sudo ldconfig
\`\`\`
"
fi

echo "$RELEASE_NOTES"

# ── Confirm ──────────────────────────────────────────────────────────────────
echo ""
printf "${BOLD}${CYAN}Ready to release:${RESET}\n"
printf "  Tag       : ${BOLD}%s${RESET}\n" "$TAG"
printf "  Asset     : dist/%s (%s)\n" "$TARBALL_NAME" "$TARBALL_SIZE"
printf "  GitLab    : %s (ID: %s)\n" "$PROJECT_PATH" "$GITLAB_PROJECT_ID"
if $DRY_RUN; then
    printf "  ${YELLOW}${BOLD}DRY RUN — no changes will be pushed${RESET}\n"
fi
echo ""

read -rp "$(printf "${BOLD}${GREEN}Proceed with release? [y/N]:${RESET} ")" confirm
case "$confirm" in
    [Yy]*) ;;
    *) die "Release cancelled" ;;
esac

# ── Create and push tag ─────────────────────────────────────────────────────
step "Tagging"

git tag -a "$TAG" -m "Release ${TAG}" 2>/dev/null || true
success "Created tag: $TAG"

if ! $DRY_RUN; then
    info "Pushing tag to origin..."
    git push origin "$TAG"
    success "Tag pushed"
else
    info "[DRY RUN] Would push tag: $TAG"
fi

# ── Upload asset to GitLab package registry ──────────────────────────────────
step "Uploading Release Assets"

TARBALL_URL=""
SHA256_URL=""

if ! $DRY_RUN; then
    # Upload tarball via generic package registry
    info "Uploading ${TARBALL_NAME}..."
    UPLOAD_RESP="$(curl -sf \
        --header "PRIVATE-TOKEN: ${GITLAB_TOKEN}" \
        --upload-file "dist/${TARBALL_NAME}" \
        "${GITLAB_API_URL}/projects/${GITLAB_PROJECT_ID}/packages/generic/${PKG_NAME}/${VERSION}/${TARBALL_NAME}" \
        2>/dev/null || echo "")"

    if [[ -z "$UPLOAD_RESP" ]] || echo "$UPLOAD_RESP" | jq -e '.message' >/dev/null 2>&1; then
        error "Failed to upload tarball"
        echo "$UPLOAD_RESP" | jq . 2>/dev/null || echo "$UPLOAD_RESP"
        die "Asset upload failed"
    fi
    TARBALL_URL="${GITLAB_API_URL}/projects/${GITLAB_PROJECT_ID}/packages/generic/${PKG_NAME}/${VERSION}/${TARBALL_NAME}"
    success "Uploaded: ${TARBALL_NAME}"

    # Upload sha256
    info "Uploading ${SHA256_NAME}..."
    curl -sf \
        --header "PRIVATE-TOKEN: ${GITLAB_TOKEN}" \
        --upload-file "dist/${SHA256_NAME}" \
        "${GITLAB_API_URL}/projects/${GITLAB_PROJECT_ID}/packages/generic/${PKG_NAME}/${VERSION}/${SHA256_NAME}" \
        >/dev/null 2>&1 || warn "SHA256 upload failed (non-critical)"
    SHA256_URL="${GITLAB_API_URL}/projects/${GITLAB_PROJECT_ID}/packages/generic/${PKG_NAME}/${VERSION}/${SHA256_NAME}"
    success "Uploaded: ${SHA256_NAME}"
else
    info "[DRY RUN] Would upload: dist/${TARBALL_NAME}"
    info "[DRY RUN] Would upload: dist/${SHA256_NAME}"
    TARBALL_URL="https://example.com/dry-run/${TARBALL_NAME}"
    SHA256_URL="https://example.com/dry-run/${SHA256_NAME}"
fi

# ── Create GitLab release ───────────────────────────────────────────────────
step "Creating GitLab Release"

# Build the release JSON payload
RELEASE_JSON="$(jq -n \
    --arg tag "$TAG" \
    --arg name "zexc ${TAG}" \
    --arg desc "$RELEASE_NOTES" \
    --arg tarball_name "$TARBALL_NAME" \
    --arg tarball_url "$TARBALL_URL" \
    --arg sha_name "$SHA256_NAME" \
    --arg sha_url "$SHA256_URL" \
    '{
        tag_name: $tag,
        name: $name,
        description: $desc,
        assets: {
            links: [
                {
                    name: $tarball_name,
                    url: $tarball_url,
                    filepath: ("/" + $tarball_name),
                    link_type: "package"
                },
                {
                    name: $sha_name,
                    url: $sha_url,
                    filepath: ("/" + $sha_name),
                    link_type: "other"
                }
            ]
        }
    }')"

if ! $DRY_RUN; then
    RELEASE_RESP="$(curl -sf \
        --header "PRIVATE-TOKEN: ${GITLAB_TOKEN}" \
        --header "Content-Type: application/json" \
        --data "$RELEASE_JSON" \
        "${GITLAB_API_URL}/projects/${GITLAB_PROJECT_ID}/releases" \
        2>/dev/null || echo "")"

    if [[ -z "$RELEASE_RESP" ]] || echo "$RELEASE_RESP" | jq -e '.message' >/dev/null 2>&1; then
        error "Failed to create release"
        echo "$RELEASE_RESP" | jq . 2>/dev/null || echo "$RELEASE_RESP"
        die "Release creation failed"
    fi

    RELEASE_URL="$(echo "$RELEASE_RESP" | jq -r '._links.self // empty')"
    success "Release created!"
else
    info "[DRY RUN] Would create release with payload:"
    echo "$RELEASE_JSON" | jq .
fi

# ── Done ─────────────────────────────────────────────────────────────────────
step "Release Complete! 🎉"
echo ""
printf "  ${BOLD}Tag${RESET}      : %s\n" "$TAG"
printf "  ${BOLD}Version${RESET}  : %s\n" "$VERSION"
printf "  ${BOLD}Tarball${RESET}  : %s (%s)\n" "$TARBALL_NAME" "$TARBALL_SIZE"
printf "  ${BOLD}SHA256${RESET}   : %s\n" "$TARBALL_SHA"
if ! $DRY_RUN; then
    printf "  ${BOLD}Release${RESET}  : https://gitlab.com/%s/-/releases/%s\n" "$PROJECT_PATH" "$TAG"
else
    printf "  ${YELLOW}${BOLD}DRY RUN${RESET}  : No changes were made\n"
fi
echo ""
success "Done."
