#!/usr/bin/env python3
"""Startup script for the Wix Form Handler API.

This script:
1. Runs database migrations using Alembic
2. Starts the FastAPI application with uvicorn

Database migrations are run BEFORE starting the server to ensure the schema
is up to date. This approach works well with multiple workers since migrations
complete before any worker starts processing requests.
"""

import sys

import uvicorn

from alpine_bits_python.run_migrations import run_migrations

if __name__ == "__main__":
    # Run database migrations before starting the server
    # This ensures the schema is up to date before any workers start
    print("Running database migrations...")
    try:
        run_migrations()
        print("Database migrations completed successfully")
    except Exception as e:
        print(f"Failed to run migrations: {e}", file=sys.stderr)
        sys.exit(1)

    # Start the API server
    print("Starting API server...")
    uvicorn.run(
        "alpine_bits_python.api:app",
        host="0.0.0.0",
        port=8080,
        reload=True,  # Enable auto-reload during development
        log_level="info",
    )
