#!/bin/bash
# Script to create the mosaic coordinator bot user in Gitea
# Usage: ./scripts/coordinator/create-gitea-bot.sh

set -e

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

# Configuration
GITEA_URL="${GITEA_URL:-https://git.mosaicstack.dev}"
ADMIN_TOKEN="${ADMIN_TOKEN:-}"
BOT_USERNAME="mosaic"
BOT_EMAIL="mosaic@mosaicstack.dev"
REPO_OWNER="mosaic"
REPO_NAME="stack"

# Check dependencies
command -v curl >/dev/null 2>&1 || { echo -e "${RED}curl is required but not installed.${NC}"; exit 1; }
command -v jq >/dev/null 2>&1 || { echo -e "${RED}jq is required but not installed.${NC}"; exit 1; }

# Functions
print_header() {
    echo -e "\n${BLUE}========================================${NC}"
    echo -e "${BLUE}$1${NC}"
    echo -e "${BLUE}========================================${NC}\n"
}

print_success() {
    echo -e "${GREEN}✓ $1${NC}"
}

print_error() {
    echo -e "${RED}✗ $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}! $1${NC}"
}

print_info() {
    echo -e "${BLUE}ℹ $1${NC}"
}

# Check for admin token
if [ -z "$ADMIN_TOKEN" ]; then
    print_error "ADMIN_TOKEN environment variable not set"
    echo -e "\n${YELLOW}To use this script, you need Gitea admin credentials:${NC}"
    echo "1. Log in to $GITEA_URL as admin"
    echo "2. Go to Settings → Access Tokens"
    echo "3. Create new token with 'api' scope"
    echo "4. Run: ADMIN_TOKEN='your-token' ./scripts/coordinator/create-gitea-bot.sh"
    exit 1
fi

# Verify Gitea connectivity
print_header "Verifying Gitea Connection"
if ! curl -s -f -H "Authorization: token $ADMIN_TOKEN" "$GITEA_URL/api/v1/user" > /dev/null; then
    print_error "Cannot connect to Gitea at $GITEA_URL"
    print_info "Verify GITEA_URL and ADMIN_TOKEN are correct"
    exit 1
fi
print_success "Connected to $GITEA_URL"

# Check if bot user already exists
print_header "Checking for Existing Bot User"
if curl -s -H "Authorization: token $ADMIN_TOKEN" \
    "$GITEA_URL/api/v1/users/$BOT_USERNAME" > /dev/null 2>&1; then
    print_warning "Bot user '$BOT_USERNAME' already exists"
    read -p "Continue anyway? (y/n) " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        print_info "Aborted"
        exit 0
    fi
else
    print_info "Bot user does not exist, will create"
fi

# Generate bot password
BOT_PASSWORD=$(openssl rand -base64 32)
print_info "Generated bot password (will be displayed at the end)"

# Create bot user
print_header "Creating Bot User"
print_info "Username: $BOT_USERNAME"
print_info "Email: $BOT_EMAIL"

BOT_RESPONSE=$(curl -s -X POST \
    -H "Authorization: token $ADMIN_TOKEN" \
    -H "Content-Type: application/json" \
    "$GITEA_URL/api/v1/admin/users" \
    -d "{
        \"username\": \"$BOT_USERNAME\",
        \"email\": \"$BOT_EMAIL\",
        \"password\": \"$BOT_PASSWORD\",
        \"must_change_password\": false,
        \"send_notify\": false,
        \"restricted\": false
    }")

# Check if user creation succeeded
if echo "$BOT_RESPONSE" | jq -e '.id' > /dev/null 2>&1; then
    BOT_ID=$(echo "$BOT_RESPONSE" | jq -r '.id')
    print_success "Bot user created with ID: $BOT_ID"
else
    if echo "$BOT_RESPONSE" | jq -e '.message' > /dev/null 2>&1; then
        ERROR_MSG=$(echo "$BOT_RESPONSE" | jq -r '.message')
        if [[ "$ERROR_MSG" == *"already exists"* ]]; then
            print_warning "User already exists, continuing..."
        else
            print_error "Failed to create user: $ERROR_MSG"
            exit 1
        fi
    else
        print_error "Failed to create bot user"
        echo "Response: $BOT_RESPONSE"
        exit 1
    fi
fi

# Add bot as repository collaborator
print_header "Adding Bot to Repository"
print_info "Repository: $REPO_OWNER/$REPO_NAME"

COLLAB_RESPONSE=$(curl -s -w "\n%{http_code}" -X PUT \
    -H "Authorization: token $ADMIN_TOKEN" \
    -H "Content-Type: application/json" \
    "$GITEA_URL/api/v1/repos/$REPO_OWNER/$REPO_NAME/collaborators/$BOT_USERNAME" \
    -d '{"permission":"push"}')

HTTP_CODE=$(echo "$COLLAB_RESPONSE" | tail -n1)
BODY=$(echo "$COLLAB_RESPONSE" | head -n-1)

if [[ "$HTTP_CODE" == "204" ]] || [[ "$HTTP_CODE" == "201" ]]; then
    print_success "Bot added as collaborator with push permission"
else
    print_error "Failed to add bot as collaborator (HTTP $HTTP_CODE)"
    echo "Response: $BODY"
    exit 1
fi

# Create access token for bot
print_header "Generating API Token"

# Need to use admin token to create token for bot user
TOKEN_RESPONSE=$(curl -s -X POST \
    -H "Authorization: token $ADMIN_TOKEN" \
    -H "Content-Type: application/json" \
    "$GITEA_URL/api/v1/admin/users/$BOT_USERNAME/tokens" \
    -d '{
        "name": "coordinator-api-token",
        "scopes": ["api", "read:repository", "write:repository", "write:issue"]
    }')

if echo "$TOKEN_RESPONSE" | jq -e '.sha1' > /dev/null 2>&1; then
    BOT_TOKEN=$(echo "$TOKEN_RESPONSE" | jq -r '.sha1')
    print_success "API token generated"
else
    print_error "Failed to generate API token"
    echo "Response: $TOKEN_RESPONSE"
    exit 1
fi

# Test bot authentication
print_header "Testing Bot Authentication"

TEST_RESPONSE=$(curl -s -w "\n%{http_code}" \
    -H "Authorization: token $BOT_TOKEN" \
    "$GITEA_URL/api/v1/user")

TEST_HTTP_CODE=$(echo "$TEST_RESPONSE" | tail -n1)
TEST_BODY=$(echo "$TEST_RESPONSE" | head -n-1)

if [[ "$TEST_HTTP_CODE" == "200" ]]; then
    TEST_USERNAME=$(echo "$TEST_BODY" | jq -r '.username')
    print_success "Bot authentication successful (username: $TEST_USERNAME)"
else
    print_error "Bot authentication failed (HTTP $TEST_HTTP_CODE)"
    exit 1
fi

# Display summary
print_header "Bot Setup Complete"

echo -e "${GREEN}Bot user created successfully!${NC}"
echo ""
echo -e "${YELLOW}Important: Save these credentials securely:${NC}"
echo ""
echo "Bot Username: $BOT_USERNAME"
echo "Bot Email: $BOT_EMAIL"
echo "Bot Password: $BOT_PASSWORD"
echo ""
echo "Bot API Token: $BOT_TOKEN"
echo ""
echo -e "${YELLOW}Next steps:${NC}"
echo "1. Store credentials in your secrets management system"
echo "2. Add to .env file (NEVER commit to git):"
echo ""
echo "   GITEA_BOT_USERNAME=$BOT_USERNAME"
echo "   GITEA_BOT_TOKEN=$BOT_TOKEN"
echo "   GITEA_BOT_PASSWORD=$BOT_PASSWORD"
echo ""
echo "3. Update .env.example with template values (no secrets)"
echo "4. Test bot functionality with: ./scripts/coordinator/test-gitea-bot.sh"
echo ""
echo -e "${BLUE}For more information, see:${NC}"
echo "   docs/1-getting-started/3-configuration/4-gitea-coordinator.md"
