#!/bin/bash

# Print environment variables for debugging
echo "Environment variables:"
echo "POSTGRES_USER: $POSTGRES_USER"
echo "POSTGRES_PASSWORD: $POSTGRES_PASSWORD"
echo "POSTGRES_DB: $POSTGRES_DB"
echo "DATABASE_URL: $DATABASE_URL"

# Function to wait for database
wait_for_db() {
    echo "Waiting for database..."
    while ! nc -z db 5432; do
        sleep 1
    done
    echo "Database is ready!"
}

# Function to create database if it doesn't exist
create_database() {
    echo "Creating database if it doesn't exist..."
    PGPASSWORD=$POSTGRES_PASSWORD psql -h db -U $POSTGRES_USER -tc "SELECT 1 FROM pg_database WHERE datname = '$POSTGRES_DB'" | grep -q 1 || \
    PGPASSWORD=$POSTGRES_PASSWORD psql -h db -U $POSTGRES_USER -c "CREATE DATABASE $POSTGRES_DB"
    echo "Database check/creation complete!"
}

# Wait for database to be ready
wait_for_db

# Create database if it doesn't exist
create_database

# Wait for PostgreSQL to be ready to accept connections
echo "Waiting for PostgreSQL to accept connections..."
until PGPASSWORD=$POSTGRES_PASSWORD psql -h db -U $POSTGRES_USER -d $POSTGRES_DB -c '\q'; do
  echo "PostgreSQL is unavailable - sleeping"
  sleep 1
done
echo "PostgreSQL is up - executing command"

# Run all initialization in a single Python script to avoid multiple Flask instances
echo "Running initialization..."
python3 -c "
import sys
from app import create_app
from models import SiteSettings, db, User
from utils.email_templates import create_default_templates

def log_error(message, error=None):
    print(f'ERROR: {message}', file=sys.stderr)
    if error:
        print(f'Error details: {str(error)}', file=sys.stderr)

app = create_app()
with app.app_context():
    try:
        # Run migrations
        print('Running database migrations...')
        from flask_migrate import upgrade
        upgrade()
        print('Database migrations completed successfully')
        
        # Create default site settings
        print('Creating default site settings...')
        try:
            settings = SiteSettings.get_settings()
            print('Default site settings created successfully')
        except Exception as e:
            log_error('Error creating site settings', e)
        
        # Create admin user if it doesn't exist
        print('Creating admin user...')
        try:
            admin = User.query.filter_by(email='administrator@docupulse.com').first()
            if not admin:
                print('Admin user not found, creating new admin user...')
                admin = User(
                    username='administrator',
                    email='administrator@docupulse.com',
                    last_name='Administrator',
                    company='DocuPulse',
                    position='System Administrator',
                    is_admin=True,
                    is_active=True,
                    preferred_view='grid'
                )
                admin.set_password('changeme')
                print('Admin user object created, attempting to add to database...')
                db.session.add(admin)
                try:
                    db.session.commit()
                    print('Default administrator user created successfully.')
                except Exception as e:
                    db.session.rollback()
                    log_error('Failed to commit admin user creation', e)
                    raise
            else:
                print('Admin user already exists.')
        except Exception as e:
            log_error('Error during admin user creation/check', e)
            raise
        
        # Create default templates
        print('Creating default templates...')
        try:
            create_default_templates()
            print('Default templates created successfully')
        except Exception as e:
            log_error('Error creating default templates', e)
    except Exception as e:
        log_error('Fatal error during initialization', e)
        sys.exit(1)
"

# Start the application
echo "Starting application..."
exec gunicorn --bind 0.0.0.0:5000 app:app 