#!/bin/bash
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

echo -e "${BLUE}🚀 Playwright + Grafana Loki Integration Test${NC}"
echo "=============================================="

# Check if Docker is running
if ! docker info > /dev/null 2>&1; then
  echo -e "${RED}❌ Docker is not running. Please start Docker first.${NC}"
  exit 1
fi

echo -e "\n${BLUE}📦 Starting local Loki stack...${NC}"
if [ -f "docker-compose.loki.yml" ]; then
  docker-compose -f docker-compose.loki.yml up -d
else
  echo -e "${YELLOW}⚠️  docker-compose.loki.yml not found. Creating basic Loki setup...${NC}"
  
  # Create temporary Loki config
  cat > /tmp/loki-config.yml << 'EOF'
auth_enabled: false

server:
  http_listen_port: 3100

ingester:
  lifecycler:
    address: 127.0.0.1
    ring:
      kvstore:
        store: inmemory
      replication_factor: 1
  chunk_idle_period: 3m
  chunk_retain_period: 1m

schema_config:
  configs:
    - from: 2020-10-24
      store: boltdb
      object_store: filesystem
      schema: v11
      index:
        prefix: index_
        period: 168h

storage_config:
  boltdb:
    directory: /tmp/loki/index
  filesystem:
    directory: /tmp/loki/chunks

limits_config:
  enforce_metric_name: false
  reject_old_samples: true
  reject_old_samples_max_age: 168h

chunk_store_config:
  max_look_back_period: 0s

table_manager:
  retention_deletes_enabled: false
  retention_period: 0s
EOF

  # Start Loki container
  docker run -d \
    --name loki-test \
    -p 3100:3100 \
    -v /tmp/loki-config.yml:/etc/loki/local-config.yaml \
    grafana/loki:2.9.0 \
    -config.file=/etc/loki/local-config.yaml
  
  # Start Grafana container
  docker run -d \
    --name grafana-test \
    -p 3000:3000 \
    -e "GF_AUTH_ANONYMOUS_ENABLED=true" \
    -e "GF_AUTH_ANONYMOUS_ORG_ROLE=Admin" \
    grafana/grafana:10.1.0
fi

# Wait for Loki to be ready
echo -e "\n${YELLOW}⏳ Waiting for Loki to start...${NC}"
max_attempts=30
attempt=0
until curl -s http://localhost:3100/ready | grep -q "ready" || [ $attempt -eq $max_attempts ]; do
  sleep 2
  attempt=$((attempt + 1))
  echo -n "."
done
echo ""

if [ $attempt -eq $max_attempts ]; then
  echo -e "${RED}❌ Loki failed to start within 60 seconds${NC}"
  exit 1
fi

echo -e "${GREEN}✅ Loki is ready${NC}"

# Export environment variables
export GRAFANA_LOKI_URL="http://localhost:3100"
export GRAFANA_LOKI_USERNAME=""
export GRAFANA_LOKI_PASSWORD=""

echo -e "\n${BLUE}🧪 Running a test Playwright test...${NC}"
# Check if tests directory exists
if [ -d "tests/e2e" ]; then
  npx playwright test tests/e2e/auth/login.spec.ts --project=chromium --reporter=./tests/helpers/loki-reporter.ts 2>&1 || true
else
  echo -e "${YELLOW}⚠️  No test files found. Skipping test execution.${NC}"
fi

# Wait a moment for logs to be ingested
sleep 3

echo -e "\n${BLUE}🔍 Querying Loki for test logs...${NC}"
start_time=$(date -u -d '5 minutes ago' +%s)000000000
end_time=$(date -u +%s)000000000

response=$(curl -s -G "http://localhost:3100/loki/api/v1/query_range" \
  --data-urlencode 'query={job="playwright-tests"}' \
  --data-urlencode "start=$start_time" \
  --data-urlencode "end=$end_time")

# Check if we got results
result_count=$(echo "$response" | jq '.data.result | length')

if [ "$result_count" -gt 0 ]; then
  echo -e "${GREEN}✅ Found $result_count log streams in Loki${NC}"
  echo -e "\n${BLUE}Sample logs:${NC}"
  echo "$response" | jq -r '.data.result[0].values[0:3][] | .[1]' 2>/dev/null || echo "No log content available"
else
  echo -e "${YELLOW}⚠️  No logs found in Loki. This might be expected if no tests ran.${NC}"
fi

# Display useful queries
echo -e "\n${BLUE}📊 Useful LogQL Queries:${NC}"
echo "------------------------------------"
echo "All test logs:"
echo '  {job="playwright-tests"}'
echo ""
echo "Failed tests only:"
echo '  {job="playwright-tests", status="failed"}'
echo ""
echo "Tests by browser:"
echo '  {job="playwright-tests", browser="chromium"}'
echo ""
echo "Test duration stats:"
echo '  quantile_over_time(0.95, {job="playwright-tests"} | json | unwrap duration_ms [1h])'
echo ""

# Open Grafana
echo -e "\n${GREEN}🌐 Grafana is available at: http://localhost:3000${NC}"
echo -e "${BLUE}   Default credentials: admin / admin${NC}"
echo ""
echo -e "${YELLOW}📖 To add Loki as a data source in Grafana:${NC}"
echo "   1. Go to Configuration > Data Sources"
echo "   2. Add Loki with URL: http://localhost:3100"
echo "   3. Import the dashboard from: monitoring/grafana-dashboard.json"
echo ""
echo -e "${GREEN}✅ Test complete!${NC}"
echo ""
echo -e "${BLUE}To stop the containers:${NC}"
echo "  docker stop loki-test grafana-test"
echo "  docker rm loki-test grafana-test"
echo ""
echo -e "${BLUE}To view logs in real-time:${NC}"
echo "  docker logs -f loki-test"
