#!/bin/bash
# TK-MP-Project Backend Start Script
# Complete automatic DB migration then start server

echo "Starting TK-MP-Project Backend..."
echo "Time: $(date '+%Y-%m-%d %H:%M:%S')"
echo "Environment: $(uname -s) $(uname -m)"

# Check environment variables
echo "DB Configuration:"
echo "  - DB_HOST: ${DB_HOST:-postgres}"
echo "  - DB_PORT: ${DB_PORT:-5432}"
echo "  - DB_NAME: ${DB_NAME:-tk_mp_bom}"
echo "  - DB_USER: ${DB_USER:-tkmp_user}"

# 1. Run complete DB migration
echo "Running complete DB migration..."
python scripts/complete_migrate.py

migration_result=$?
if [ $migration_result -ne 0 ]; then
    echo "WARNING: DB migration had some errors. Trying to fix missing tables..."
    python scripts/fix_missing_tables.py
    fix_result=$?
    if [ $fix_result -eq 0 ]; then
        echo "SUCCESS: Missing tables fixed"
    else
        echo "WARNING: Some tables may still be missing but starting server anyway"
    fi
else
    echo "SUCCESS: Complete DB migration finished"
fi

# Additional safety check for critical tables
echo "Verifying critical tables..."
python scripts/fix_missing_tables.py

# Complete schema analysis and fix
echo "Running complete schema analysis and fix..."
python scripts/analyze_and_fix_schema.py
echo "Complete schema analysis completed"

# Database performance optimization (run once after migration)
echo "Running database performance optimization..."
python scripts/optimize_database.py
echo "Database optimization completed"

# 2. Start FastAPI server
echo "Starting FastAPI server..."
echo "  - Port: 8000"
echo "  - Host: 0.0.0.0"
echo "  - Environment: ${ENVIRONMENT:-development}"

exec uvicorn app.main:app --host 0.0.0.0 --port 8000 --log-level info
