#!/bin/bash
# Test Authentik blueprint import after manual setup

set -euo pipefail

# 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
DOMAIN=${DOMAIN:-local}
AUTHENTIK_URL="https://auth.${DOMAIN}"
AUTHENTIK_API_URL="$AUTHENTIK_URL/api/v3"
ADMIN_EMAIL="admin@local.local"
ADMIN_PASSWORD="${AUTHENTIK_ADMIN_PASSWORD:-admin123}"

echo -e "${BLUE}🧪 Testing Authentik blueprint import...${NC}"
echo

# Function to check if setup is complete
check_setup_complete() {
    local host
    host=$(echo "$AUTHENTIK_URL" | sed -E 's#^https?://([^/]+).*$#\1#')
    local resolve=(--resolve "${host}:443:127.0.0.1")
    local setup_code
    setup_code=$(curl -ks "${resolve[@]}" -o /dev/null -w '%{http_code}' "$AUTHENTIK_URL/if/flow/initial-setup/" || true)

    if [[ "$setup_code" == "404" ]]; then
        return 0  # Setup is complete
    else
        return 1  # Setup is still needed
    fi
}

# Function to get API token via login
get_api_token_via_login() {
    echo -e "${YELLOW}🔑 Getting API token via login...${NC}"

    local host
    host=$(echo "$AUTHENTIK_URL" | sed -E 's#^https?://([^/]+).*$#\1#')
    local resolve=(--resolve "${host}:443:127.0.0.1")

    # Get login page and extract CSRF token
    local login_page
    login_page=$(curl -ks "${resolve[@]}" -c /tmp/auth_cookies.txt "$AUTHENTIK_URL/if/flow/default-authentication-flow/" || echo "")

    if [ -z "$login_page" ]; then
        echo -e "${RED}❌ Could not access login page${NC}"
        return 1
    fi

    # Extract CSRF token from the page
    local csrf_token
    csrf_token=$(echo "$login_page" | grep -o 'name="csrfmiddlewaretoken"[^>]*value="[^"]*"' | sed 's/.*value="\([^"]*\)".*/\1/' | head -1 || echo "")

    if [ -z "$csrf_token" ]; then
        echo -e "${RED}❌ Could not extract CSRF token${NC}"
        return 1
    fi

    echo -e "${GREEN}✅ CSRF token extracted${NC}"

    # Login
    local login_response
    login_response=$(curl -ks "${resolve[@]}" -b /tmp/auth_cookies.txt -c /tmp/auth_cookies.txt \
        -X POST "$AUTHENTIK_URL/if/flow/default-authentication-flow/" \
        -H "Content-Type: application/x-www-form-urlencoded" \
        -H "Referer: $AUTHENTIK_URL/if/flow/default-authentication-flow/" \
        -d "csrfmiddlewaretoken=$csrf_token&uid_field=$ADMIN_EMAIL&password=$ADMIN_PASSWORD" \
        -w '%{http_code}' -o /tmp/login_response.html || echo "")

    if [[ "$login_response" =~ ^(200|302)$ ]]; then
        echo -e "${GREEN}✅ Login successful${NC}"

        # Get admin interface page to get new CSRF token
        local admin_page
        admin_page=$(curl -ks "${resolve[@]}" -b /tmp/auth_cookies.txt "$AUTHENTIK_URL/if/admin/" || echo "")

        local admin_csrf
        admin_csrf=$(echo "$admin_page" | grep -o 'name="csrfmiddlewaretoken"[^>]*value="[^"]*"' | sed 's/.*value="\([^"]*\)".*/\1/' | head -1 || echo "")

        if [ -n "$admin_csrf" ]; then
            # Create API token
            local token_response
            token_response=$(curl -ks "${resolve[@]}" -b /tmp/auth_cookies.txt \
                -X POST "$AUTHENTIK_API_URL/core/tokens/" \
                -H "Content-Type: application/json" \
                -H "X-CSRFToken: $admin_csrf" \
                -d "{
                    \"identifier\": \"blueprint-test-$(date +%s)\",
                    \"description\": \"Test token for blueprint import\",
                    \"expires\": \"2025-12-31T23:59:59Z\"
                }" 2>/dev/null || echo "")

            if [ -n "$token_response" ]; then
                local token
                token=$(echo "$token_response" | python3 -c "import sys, json; print(json.load(sys.stdin)['key'])" 2>/dev/null || echo "")

                if [ -n "$token" ]; then
                    echo -e "${GREEN}✅ API token created${NC}"
                    echo "$token"
                    return 0
                fi
            fi
        fi
    fi

    echo -e "${RED}❌ Failed to get API token${NC}"
    return 1
}

# Function to import blueprint
import_blueprint() {
    local token="$1"

    echo -e "${YELLOW}📋 Importing blueprint...${NC}"

    local host
    host=$(echo "$AUTHENTIK_URL" | sed -E 's#^https?://([^/]+).*$#\1#')
    local resolve=(--resolve "${host}:443:127.0.0.1")

    # Create blueprint instance
    local blueprint_response
    blueprint_response=$(curl -ks "${resolve[@]}" \
        -X POST "$AUTHENTIK_API_URL/managed/blueprints/" \
        -H "Content-Type: application/json" \
        -H "Authorization: Bearer $token" \
        -d '{
            "name": "AI Tax Agent Bootstrap",
            "path": "/blueprints/bootstrap.yaml",
            "context": {},
            "enabled": true
        }' 2>/dev/null || echo "")

    echo -e "${BLUE}Blueprint creation response:${NC}"
    echo "$blueprint_response" | python3 -c "import sys, json; print(json.dumps(json.load(sys.stdin), indent=2))" 2>/dev/null || echo "$blueprint_response"

    local blueprint_pk
    blueprint_pk=$(echo "$blueprint_response" | python3 -c "import sys, json; print(json.load(sys.stdin).get('pk', ''))" 2>/dev/null || echo "")

    if [ -n "$blueprint_pk" ]; then
        echo -e "${GREEN}✅ Blueprint created with ID: $blueprint_pk${NC}"

        # Apply the blueprint
        echo -e "${YELLOW}🔄 Applying blueprint...${NC}"
        local apply_response
        apply_response=$(curl -ks "${resolve[@]}" \
            -X POST "$AUTHENTIK_API_URL/managed/blueprints/$blueprint_pk/apply/" \
            -H "Content-Type: application/json" \
            -H "Authorization: Bearer $token" \
            -d '{}' 2>/dev/null || echo "")

        echo -e "${BLUE}Blueprint apply response:${NC}"
        echo "$apply_response" | python3 -c "import sys, json; print(json.dumps(json.load(sys.stdin), indent=2))" 2>/dev/null || echo "$apply_response"

        return 0
    else
        echo -e "${RED}❌ Failed to create blueprint${NC}"
        return 1
    fi
}

# Main function
main() {
    # Check if setup is complete
    if ! check_setup_complete; then
        echo -e "${YELLOW}⚠️  Initial setup is still required${NC}"
        echo -e "${BLUE}📋 Please complete setup at: https://auth.local.lan.lan/if/flow/initial-setup/${NC}"
        echo -e "${BLUE}Use credentials: admin@local.local / admin123${NC}"
        return 1
    fi

    echo -e "${GREEN}✅ Initial setup is complete${NC}"

    # Get API token
    local api_token
    if api_token=$(get_api_token_via_login); then
        echo -e "${GREEN}🔑 API token obtained${NC}"

        # Import blueprint
        if import_blueprint "$api_token"; then
            echo -e "${GREEN}🎉 Blueprint import test completed!${NC}"
        else
            echo -e "${RED}❌ Blueprint import failed${NC}"
            return 1
        fi
    else
        echo -e "${RED}❌ Could not get API token${NC}"
        return 1
    fi

    # Cleanup
    rm -f /tmp/auth_cookies.txt /tmp/login_response.html
}

# Run main function
main "$@"
