#!/bin/bash

# Convenience script: Clean databases and regenerate all migrations in one command
# This wraps the two-step process into a single workflow

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
NAMESPACE="${KUBE_NAMESPACE:-bakery-ia}"
SKIP_CONFIRMATION=false
APPLY_MIGRATIONS=false
VERBOSE=false

# Parse command line arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --namespace) NAMESPACE="$2"; shift 2 ;;
        --yes) SKIP_CONFIRMATION=true; shift ;;
        --apply) APPLY_MIGRATIONS=true; shift ;;
        --verbose) VERBOSE=true; shift ;;
        -h|--help)
            echo "Usage: $0 [OPTIONS]"
            echo ""
            echo "This script performs the complete migration regeneration workflow:"
            echo "  1. Clean all service databases"
            echo "  2. Generate new migrations from models"
            echo "  3. Optionally apply migrations"
            echo ""
            echo "Options:"
            echo "  --namespace NAME  Use specific Kubernetes namespace (default: bakery-ia)"
            echo "  --yes             Skip all confirmation prompts"
            echo "  --apply           Apply migrations after generation"
            echo "  --verbose         Enable detailed logging"
            echo ""
            echo "Examples:"
            echo "  $0                    # Interactive mode (with confirmations)"
            echo "  $0 --yes --verbose    # Automated mode with detailed output"
            echo "  $0 --apply            # Generate and apply migrations"
            exit 0
            ;;
        *) echo "Unknown option: $1"; echo "Use --help for usage information"; exit 1 ;;
    esac
done

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}Complete Migration Regeneration Workflow${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""
echo -e "${YELLOW}This script will:${NC}"
echo -e "${YELLOW}  1. Clean all service databases (DROP all tables)${NC}"
echo -e "${YELLOW}  2. Generate new migrations from models${NC}"
if [ "$APPLY_MIGRATIONS" = true ]; then
    echo -e "${YELLOW}  3. Apply migrations to databases${NC}"
fi
echo ""
echo -e "${YELLOW}Namespace: $NAMESPACE${NC}"
echo ""

if [ "$SKIP_CONFIRMATION" = false ]; then
    echo -e "${RED}⚠  WARNING: This will DROP ALL TABLES in all service databases!${NC}"
    echo ""
    read -p "Continue? (yes/no) " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        echo -e "${YELLOW}Aborted.${NC}"
        exit 0
    fi
fi

echo ""
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}Step 1: Cleaning Databases${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

# Build cleanup command
CLEANUP_CMD="./cleanup_databases_k8s.sh --namespace $NAMESPACE"
if [ "$SKIP_CONFIRMATION" = true ]; then
    CLEANUP_CMD="$CLEANUP_CMD --yes"
fi

# Run cleanup
if ! $CLEANUP_CMD; then
    echo -e "${RED}✗ Database cleanup failed!${NC}"
    echo -e "${YELLOW}Cannot proceed with migration generation.${NC}"
    exit 1
fi

echo ""
echo -e "${GREEN}✓ Database cleanup completed${NC}"
echo ""

# Wait a moment for database connections to settle
sleep 2

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}Step 2: Generating Migrations${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

# Build migration command
MIGRATION_CMD="./regenerate_migrations_k8s.sh --namespace $NAMESPACE"
if [ "$VERBOSE" = true ]; then
    MIGRATION_CMD="$MIGRATION_CMD --verbose"
fi
if [ "$APPLY_MIGRATIONS" = true ]; then
    MIGRATION_CMD="$MIGRATION_CMD --apply"
fi

# Run migration generation (with automatic 'y' response)
if [ "$SKIP_CONFIRMATION" = true ]; then
    echo "y" | $MIGRATION_CMD
else
    $MIGRATION_CMD
fi

MIGRATION_EXIT_CODE=$?

echo ""
if [ $MIGRATION_EXIT_CODE -eq 0 ]; then
    echo -e "${GREEN}========================================${NC}"
    echo -e "${GREEN}✓ Workflow Completed Successfully!${NC}"
    echo -e "${GREEN}========================================${NC}"
    echo ""
    echo -e "${YELLOW}Summary:${NC}"
    echo -e "  ${GREEN}✓${NC} Databases cleaned"
    echo -e "  ${GREEN}✓${NC} Migrations generated"
    if [ "$APPLY_MIGRATIONS" = true ]; then
        echo -e "  ${GREEN}✓${NC} Migrations applied"
    fi
    echo ""
    echo -e "${YELLOW}Generated migration files:${NC}"
    find services/*/migrations/versions/ -name "*.py" -type f -mmin -5 2>/dev/null | while read file; do
        size=$(wc -c < "$file" | tr -d ' ')
        echo -e "  ${GREEN}✓${NC} $file ($size bytes)"
    done
    echo ""
    echo -e "${YELLOW}Next steps:${NC}"
    echo -e "  1. Review the generated migrations above"
    echo -e "  2. Verify migrations contain schema operations (not just 'pass')"
    if [ "$APPLY_MIGRATIONS" = false ]; then
        echo -e "  3. Apply migrations: ./regenerate_migrations_k8s.sh --apply"
        echo -e "  4. Commit migrations: git add services/*/migrations/versions/*.py"
    else
        echo -e "  3. Commit migrations: git add services/*/migrations/versions/*.py"
    fi
else
    echo -e "${RED}========================================${NC}"
    echo -e "${RED}✗ Migration Generation Failed${NC}"
    echo -e "${RED}========================================${NC}"
    echo ""
    echo -e "${YELLOW}Check the log file for details.${NC}"
    echo -e "${YELLOW}Common issues:${NC}"
    echo -e "  - Pod not running for some services"
    echo -e "  - Database connectivity issues"
    echo -e "  - Model import errors"
    echo ""
    exit 1
fi
