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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
#!/bin/bash
#
# AudioForge Master Launch Script
# Orchestrates the complete launch process with zero-downtime deployment
#
# Usage:
#   ./scripts/launch.sh [--environment ENV] [--skip-tests] [--dry-run]
#
# Options:
#   --environment ENV    Target environment (development|staging|production)
#   --skip-tests         Skip test suite (not recommended for production)
#   --dry-run           Show what would be done without executing
#   --help              Show this help message

set -euo pipefail

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# Default values
ENVIRONMENT="${ENVIRONMENT:-development}"
SKIP_TESTS=false
DRY_RUN=false
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

# Parse arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --environment)
            ENVIRONMENT="$2"
            shift 2
            ;;
        --skip-tests)
            SKIP_TESTS=true
            shift
            ;;
        --dry-run)
            DRY_RUN=true
            shift
            ;;
        --help)
            grep '^#' "$0" | cut -c 3-
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            echo "Use --help for usage information"
            exit 1
            ;;
    esac
done

# Logging functions
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_step() {
    echo -e "\n${PURPLE}═══${NC} ${CYAN}$1${NC} ${PURPLE}═══${NC}\n"
}

# Check if command exists
command_exists() {
    command -v "$1" >/dev/null 2>&1
}

# Execute or print command based on dry-run mode
execute() {
    if [ "$DRY_RUN" = true ]; then
        echo -e "${YELLOW}[DRY-RUN]${NC} Would execute: $*"
    else
        "$@"
    fi
}

# Verify prerequisites
verify_prerequisites() {
    log_step "Verifying Prerequisites"
    
    local missing_deps=()
    
    # Check Python
    if ! command_exists python3; then
        missing_deps+=("python3")
    else
        python_version=$(python3 --version | cut -d' ' -f2)
        log_info "Python version: $python_version"
    fi
    
    # Check Node.js
    if ! command_exists node; then
        missing_deps+=("node")
    else
        node_version=$(node --version)
        log_info "Node version: $node_version"
    fi
    
    # Check pnpm
    if ! command_exists pnpm; then
        log_warning "pnpm not found, installing..."
        npm install -g pnpm
    fi
    
    # Check Docker (optional)
    if command_exists docker; then
        docker_version=$(docker --version)
        log_info "Docker version: $docker_version"
    fi
    
    if [ ${#missing_deps[@]} -gt 0 ]; then
        log_error "Missing dependencies: ${missing_deps[*]}"
        exit 1
    fi
    
    log_success "All prerequisites satisfied"
}

# Run verification checks
run_verification() {
    log_step "Running Verification Checks"
    
    cd "$PROJECT_ROOT"
    
    if [ "$DRY_RUN" = false ]; then
        python3 scripts/launch_verification.py --verbose --json launch-verification.json
        
        # Check if verification passed
        if [ $? -ne 0 ]; then
            log_error "Verification failed! Please fix issues before launching."
            exit 1
        fi
    else
        log_info "Would run: python3 scripts/launch_verification.py"
    fi
    
    log_success "Verification checks passed"
}

# Setup environment
setup_environment() {
    log_step "Setting Up Environment: $ENVIRONMENT"
    
    cd "$PROJECT_ROOT"
    
    # Backend environment
    if [ ! -f "backend/.env" ]; then
        log_warning "Backend .env not found, creating from example..."
        execute cp backend/.env.example backend/.env
        log_warning "Please configure backend/.env before proceeding"
        
        if [ "$ENVIRONMENT" = "production" ]; then
            log_error "Production environment requires configured .env file"
            exit 1
        fi
    fi
    
    # Frontend environment
    if [ ! -f "frontend/.env.local" ]; then
        log_warning "Frontend .env.local not found, creating..."
        if [ "$ENVIRONMENT" = "production" ]; then
            echo "NEXT_PUBLIC_API_URL=https://api.yourdomain.com" > frontend/.env.local
        else
            echo "NEXT_PUBLIC_API_URL=http://localhost:8000" > frontend/.env.local
        fi
    fi
    
    log_success "Environment configured"
}

# Install dependencies
install_dependencies() {
    log_step "Installing Dependencies"
    
    # Backend dependencies
    log_info "Installing backend dependencies..."
    cd "$PROJECT_ROOT/backend"
    execute pip install -e ".[dev]"
    
    # Frontend dependencies
    log_info "Installing frontend dependencies..."
    cd "$PROJECT_ROOT/frontend"
    execute pnpm install --frozen-lockfile
    
    log_success "Dependencies installed"
}

# Run tests
run_tests() {
    if [ "$SKIP_TESTS" = true ]; then
        log_warning "Skipping tests (--skip-tests flag)"
        return
    fi
    
    log_step "Running Test Suite"
    
    # Backend tests
    log_info "Running backend tests..."
    cd "$PROJECT_ROOT/backend"
    execute pytest tests/ -v --cov=app
    
    # Frontend tests
    log_info "Running frontend tests..."
    cd "$PROJECT_ROOT/frontend"
    execute pnpm test
    
    # Type checking
    log_info "Running type checks..."
    execute pnpm run type-check
    
    log_success "All tests passed"
}

# Build applications
build_applications() {
    log_step "Building Applications"
    
    # Frontend build
    log_info "Building frontend..."
    cd "$PROJECT_ROOT/frontend"
    execute pnpm run build
    
    log_success "Applications built successfully"
}

# Database setup
setup_database() {
    log_step "Setting Up Database"
    
    cd "$PROJECT_ROOT/backend"
    
    # Run migrations
    log_info "Running database migrations..."
    execute python scripts/init_db.py
    
    log_success "Database initialized"
}

# Start services
start_services() {
    log_step "Starting Services"
    
    cd "$PROJECT_ROOT"
    
    if command_exists docker-compose; then
        log_info "Starting services with Docker Compose..."
        execute docker-compose up -d
        
        # Wait for services to be healthy
        if [ "$DRY_RUN" = false ]; then
            log_info "Waiting for services to be healthy..."
            sleep 10
            
            # Check backend health
            for i in {1..30}; do
                if curl -f http://localhost:8000/health >/dev/null 2>&1; then
                    log_success "Backend is healthy"
                    break
                fi
                sleep 2
            done
            
            # Check frontend health
            for i in {1..30}; do
                if curl -f http://localhost:3000 >/dev/null 2>&1; then
                    log_success "Frontend is healthy"
                    break
                fi
                sleep 2
            done
        fi
    else
        log_warning "Docker Compose not available, starting services manually..."
        
        # Start backend
        log_info "Starting backend..."
        cd "$PROJECT_ROOT/backend"
        execute uvicorn app.main:app --host 0.0.0.0 --port 8000 &
        BACKEND_PID=$!
        
        # Start frontend
        log_info "Starting frontend..."
        cd "$PROJECT_ROOT/frontend"
        execute pnpm start &
        FRONTEND_PID=$!
        
        # Save PIDs
        echo $BACKEND_PID > "$PROJECT_ROOT/.backend.pid"
        echo $FRONTEND_PID > "$PROJECT_ROOT/.frontend.pid"
    fi
    
    log_success "Services started"
}

# Generate launch report
generate_report() {
    log_step "Generating Launch Report"
    
    cd "$PROJECT_ROOT"
    execute python3 scripts/generate_launch_report.py
    
    log_success "Launch report generated: LAUNCH_REPORT.html"
}

# Post-launch verification
post_launch_verification() {
    log_step "Post-Launch Verification"
    
    if [ "$DRY_RUN" = false ]; then
        # Test backend
        log_info "Testing backend endpoint..."
        if curl -f http://localhost:8000/health; then
            log_success "Backend responding"
        else
            log_error "Backend not responding"
            exit 1
        fi
        
        # Test frontend
        log_info "Testing frontend..."
        if curl -f http://localhost:3000; then
            log_success "Frontend responding"
        else
            log_error "Frontend not responding"
            exit 1
        fi
        
        # Test API endpoints
        log_info "Testing API endpoints..."
        if curl -f http://localhost:8000/api/v1/generations; then
            log_success "API endpoints accessible"
        else
            log_warning "API endpoints returned error (may be expected if no data)"
        fi
    fi
    
    log_success "Post-launch verification complete"
}

# Main execution
main() {
    echo -e "${PURPLE}"
    cat << "EOF"
    ╔═══════════════════════════════════════════════════════════╗
    β•‘                                                           β•‘
    β•‘              🎡 AudioForge Launch System 🎡              β•‘
    β•‘                                                           β•‘
    β•‘                  Forged by FusionPanda                    β•‘
    β•‘                                                           β•‘
    β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
EOF
    echo -e "${NC}"
    
    log_info "Environment: $ENVIRONMENT"
    log_info "Skip Tests: $SKIP_TESTS"
    log_info "Dry Run: $DRY_RUN"
    echo ""
    
    # Execute launch sequence
    verify_prerequisites
    run_verification
    setup_environment
    install_dependencies
    run_tests
    build_applications
    setup_database
    start_services
    generate_report
    post_launch_verification
    
    # Success message
    echo -e "\n${GREEN}"
    cat << "EOF"
    ╔═══════════════════════════════════════════════════════════╗
    β•‘                                                           β•‘
    β•‘              πŸŽ‰ LAUNCH SUCCESSFUL! πŸŽ‰                    β•‘
    β•‘                                                           β•‘
    β•‘         AudioForge is now running and ready!              β•‘
    β•‘                                                           β•‘
    β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
EOF
    echo -e "${NC}"
    
    echo ""
    log_success "Backend: http://localhost:8000"
    log_success "Frontend: http://localhost:3000"
    log_success "API Docs: http://localhost:8000/docs"
    log_success "Launch Report: file://$PROJECT_ROOT/LAUNCH_REPORT.html"
    echo ""
    
    if [ "$ENVIRONMENT" = "production" ]; then
        log_warning "Production deployment complete. Monitor logs and metrics closely."
    fi
    
    log_info "🐼⚑ The panda has spoken. The launch is complete. 🎡"
}

# Trap errors
trap 'log_error "Launch failed at line $LINENO"' ERR

# Run main function
main