#!/bin/bash
# Script to provision Azure DevOps repository for RAG API

set -e

# Configuration
PROJECT_NAME=${1:-"edenred"}
REPO_NAME=${2:-"agenred-agentic-rag-api"}
AZURE_DEVOPS_ORG=${3:-"https://dev.azure.com/edenred"}
PAT_TOKEN=${AZURE_DEVOPS_PAT:-""}

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

echo -e "${YELLOW}================================================${NC}"
echo -e "${YELLOW}Azure DevOps Repository Provisioning${NC}"
echo -e "${YELLOW}================================================${NC}"

# Check requirements
if ! command -v az &> /dev/null; then
    echo -e "${RED}❌ Azure CLI is not installed. Install it first:${NC}"
    echo "   https://learn.microsoft.com/en-us/cli/azure/install-azure-cli"
    exit 1
fi

if [ -z "$PAT_TOKEN" ]; then
    echo -e "${YELLOW}⚠️  AZURE_DEVOPS_PAT environment variable not set${NC}"
    echo "   Set it with your Personal Access Token:"
    echo "   export AZURE_DEVOPS_PAT='your-pat-token'"
    echo ""
    echo "   To create a PAT:"
    echo "   1. Go to https://dev.azure.com/edenred/_usersSettings/tokens"
    echo "   2. Create a new token with 'Code (read & write)', 'Project & Team', 'Release (read, write & execute)'"
    read -p "   Enter your PAT token: " PAT_TOKEN
fi

if [ -z "$PAT_TOKEN" ]; then
    echo -e "${RED}❌ PAT token is required${NC}"
    exit 1
fi

# Login to Azure DevOps
echo -e "${YELLOW}🔐 Logging in to Azure DevOps...${NC}"
echo "$PAT_TOKEN" | az devops login --organization "$AZURE_DEVOPS_ORG"

# Set default org and project
echo -e "${YELLOW}⚙️  Setting up defaults...${NC}"
az devops configure --defaults organization="$AZURE_DEVOPS_ORG" project="$PROJECT_NAME"

# Check if project exists
echo -e "${YELLOW}🔍 Checking if project exists...${NC}"
PROJECT_ID=$(az devops project show --project "$PROJECT_NAME" --query id -o tsv 2>/dev/null || echo "")

if [ -z "$PROJECT_ID" ]; then
    echo -e "${RED}❌ Project '$PROJECT_NAME' not found${NC}"
    echo "   Create the project first in Azure DevOps web interface"
    exit 1
fi

echo -e "${GREEN}✅ Project found: $PROJECT_ID${NC}"

# Check if repo already exists
echo -e "${YELLOW}🔍 Checking if repository already exists...${NC}"
REPO_ID=$(az repos list --project "$PROJECT_NAME" --query "[?name=='$REPO_NAME'].id | [0]" -o tsv 2>/dev/null || echo "")

if [ ! -z "$REPO_ID" ]; then
    echo -e "${GREEN}✅ Repository already exists: $REPO_ID${NC}"
    REPO_URL=$(az repos show --project "$PROJECT_NAME" --repository "$REPO_NAME" --query webUrl -o tsv)
    echo -e "${GREEN}📍 Repository URL: $REPO_URL${NC}"
else
    echo -e "${YELLOW}📝 Creating repository...${NC}"
    az repos create --project "$PROJECT_NAME" --name "$REPO_NAME"

    REPO_ID=$(az repos list --project "$PROJECT_NAME" --query "[?name=='$REPO_NAME'].id | [0]" -o tsv)
    REPO_URL=$(az repos show --project "$PROJECT_NAME" --repository "$REPO_NAME" --query webUrl -o tsv)

    echo -e "${GREEN}✅ Repository created: $REPO_ID${NC}"
    echo -e "${GREEN}📍 Repository URL: $REPO_URL${NC}"
fi

# Get clone URL
CLONE_URL=$(az repos show --project "$PROJECT_NAME" --repository "$REPO_NAME" --query "{HTTP: webUrl}" -o tsv)

echo -e "${YELLOW}📦 Cloning repository...${NC}"
TEMP_DIR=$(mktemp -d)
cd "$TEMP_DIR"

git clone "$CLONE_URL" .

echo -e "${YELLOW}📂 Copying Phase 2 scaffold...${NC}"

# Copy from local framework repo (adjust path as needed)
SCAFFOLD_PATH="../stacks/agenred-rag-api"
if [ ! -d "$SCAFFOLD_PATH" ]; then
    echo -e "${RED}❌ Scaffold not found at $SCAFFOLD_PATH${NC}"
    exit 1
fi

# Copy all files from scaffold
cp -r "$SCAFFOLD_PATH"/* .
cp "$SCAFFOLD_PATH"/.env.example .
cp "$SCAFFOLD_PATH"/.github/workflows/* .github/workflows/ 2>/dev/null || mkdir -p .github/workflows

echo -e "${YELLOW}🔧 Setting up repository...${NC}"

# Create .gitignore
cat > .gitignore <<EOF
node_modules/
dist/
coverage/
.env
.env.local
*.log
logs/
data/
.DS_Store
.vscode/local
exports/
EOF

# Initial commit
git add .
git commit -m "feat: Phase 2 RAG API scaffold

- Core services: ContextHubClient, HybridSearchEngine, QueryCache
- Express API with /query, /health, /cache/stats endpoints
- Comprehensive unit tests (20+ test suites)
- Docker multi-stage build + docker-compose
- CI/CD pipelines for build and docker push
- Complete README and documentation"

echo -e "${YELLOW}📤 Pushing to Azure DevOps...${NC}"
git push -u origin main || git push -u origin master

echo -e "${YELLOW}⚙️  Setting up branch policies...${NC}"

# Create develop branch if needed
git checkout -b develop 2>/dev/null || git checkout develop
git push -u origin develop 2>/dev/null || true

# Set branch protection on main
az repos policy create \
  --branch main \
  --project "$PROJECT_NAME" \
  --repository "$REPO_NAME" \
  --type minimum_reviewer_count \
  --minimum-reviewer-count 1 \
  --creator-vote-counts false \
  --allow-downvotes false 2>/dev/null || true

echo -e "${GREEN}================================================${NC}"
echo -e "${GREEN}✅ SUCCESS! Repository provisioned${NC}"
echo -e "${GREEN}================================================${NC}"

echo ""
echo -e "${YELLOW}Repository Details:${NC}"
echo "  Name: $REPO_NAME"
echo "  URL: $REPO_URL"
echo "  Project: $PROJECT_NAME"
echo ""

echo -e "${YELLOW}Next Steps:${NC}"
echo "  1. Clone locally:"
echo "     git clone $CLONE_URL"
echo ""
echo "  2. Install dependencies:"
echo "     cd agenred-agentic-rag-api"
echo "     npm install --legacy-peer-deps"
echo ""
echo "  3. Setup environment:"
echo "     cp .env.example .env"
echo "     # Edit .env with your framework URL and API key"
echo ""
echo "  4. Run locally:"
echo "     npm run dev"
echo ""
echo "  5. Or with Docker:"
echo "     docker-compose up"
echo ""

# Cleanup
cd /
rm -rf "$TEMP_DIR"

echo -e "${GREEN}Repository ready for Phase 3 development!${NC}"
