#!/bin/bash

# Build and push script for Yandex Cloud Container Registry
# Usage: ./scripts/build-and-push. [tag]

set -e

# Configuration
REGISTRY_ID="${YANDEX_REGISTRY_ID:-your-registry-id}"
IMAGE_NAME="hr-ai-backend"
TAG="${1:-latest}"
FULL_IMAGE_NAME="cr.yandex/${REGISTRY_ID}/${IMAGE_NAME}:${TAG}"

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

echo -e "${YELLOW}Building and pushing HR AI Backend to Yandex Cloud Container Registry${NC}"

# Check if required environment variables are set
if [ -z "$REGISTRY_ID" ] || [ "$REGISTRY_ID" = "your-registry-id" ]; then
    echo -e "${RED}Error: YANDEX_REGISTRY_ID environment variable is not set${NC}"
    echo "Please set it to your Yandex Cloud Container Registry ID"
    echo "Example: export YANDEX_REGISTRY_ID=crp1234567890abcdef"
    exit 1
fi

# Check if yc CLI is installed and authenticated
if ! command -v yc &> /dev/null; then
    echo -e "${RED}Error: Yandex Cloud CLI (yc) is not installed${NC}"
    echo "Please install it from: https://cloud.yandex.ru/docs/cli/quickstart"
    exit 1
fi

# Check authentication
if ! yc config list | grep -q "token:"; then
    echo -e "${RED}Error: Not authenticated with Yandex Cloud${NC}"
    echo "Please run: yc init"
    exit 1
fi

echo -e "${YELLOW}Configuring Docker for Yandex Cloud Container Registry...${NC}"
yc container registry configure-docker

echo -e "${YELLOW}Building Docker image: ${FULL_IMAGE_NAME}${NC}"
docker build -t "${FULL_IMAGE_NAME}" .

echo -e "${YELLOW}Pushing image to registry...${NC}"
docker push "${FULL_IMAGE_NAME}"

echo -e "${GREEN}✓ Successfully built and pushed: ${FULL_IMAGE_NAME}${NC}"

# Also tag as latest if a specific tag was provided
if [ "$TAG" != "latest" ]; then
    LATEST_IMAGE_NAME="cr.yandex/${REGISTRY_ID}/${IMAGE_NAME}:latest"
    echo -e "${YELLOW}Tagging as latest...${NC}"
    docker tag "${FULL_IMAGE_NAME}" "${LATEST_IMAGE_NAME}"
    docker push "${LATEST_IMAGE_NAME}"
    echo -e "${GREEN}✓ Also pushed as: ${LATEST_IMAGE_NAME}${NC}"
fi

echo -e "${GREEN}Build and push completed successfully!${NC}"
echo ""
echo "Image is available at:"
echo "  ${FULL_IMAGE_NAME}"
echo ""
echo "To use in production, update your docker-compose.prod.yml:"
echo "  backend:"
echo "    image: ${FULL_IMAGE_NAME}"