"""
Entry point for the Employee Workstation Activity Tracking application.

This script initializes the Flask application and runs the development server.
"""
import os

# Removed unused import sys
from app import create_app, init_db
from sqlalchemy.exc import SQLAlchemyError # Import SQLAlchemyError

# Create the application instance using the factory function
app = create_app()

if __name__ == "__main__":
    # Print some diagnostic information
    # Consider using app.logger for some of these if appropriate after app init
    app.logger.info("Starting application via run.py...")  # Changed to app.logger
    app.logger.info(f"Instance path: {app.instance_path}")  # Changed to app.logger
    app.logger.info(
        f"Instance path exists: {os.path.exists(app.instance_path)}"
    )  # Changed to app.logger

    # Make sure the instance directory exists
    if not os.path.exists(app.instance_path):
        try:
            os.makedirs(app.instance_path)
            app.logger.info(
                f"Created instance directory: {app.instance_path}"
            )  # Changed to app.logger
        except OSError as e: # Changed from Exception to OSError
            app.logger.error(
                f"Error creating instance directory: {e}"
            )  # Changed to app.logger

    # Check instance directory permissions
    has_write_access = os.access(app.instance_path, os.W_OK)
    app.logger.info(
        f"Instance path write access: {has_write_access}"
    )  # Changed to app.logger

    # Print database configuration
    db_uri = app.config["SQLALCHEMY_DATABASE_URI"]
    masked_uri = db_uri
    if "@" in db_uri:
        parts = db_uri.split("@")
        masked_uri = "****@" + parts[1]
    app.logger.info(f"Database URI: {masked_uri}")  # Changed to app.logger

    # Initialize the database if needed
    try:
        app.logger.info("Initializing database from run.py...")  # Changed to app.logger
        init_db(app)  # Pass the app instance
        app.logger.info(
            "Database initialization successful from run.py"
        )  # Changed to app.logger
    except SQLAlchemyError as db_e: # Specific for DB issues
        app.logger.error(f"Database error during initialization from run.py: {db_e}")
        # Optionally log full traceback for SQLAlchemyErrors if they are complex
        # import traceback
        # app.logger.error(traceback.format_exc())
    except Exception as e: # For other unexpected errors during init
        app.logger.error(
            f"Unexpected error during database initialization from run.py: {e}"
        )  # Changed to app.logger
        import traceback

    # Run the Flask application
    host = os.environ.get("HOST", "0.0.0.0")
    port = int(os.environ.get("PORT", 5000))
    debug = os.environ.get("DEBUG", "False").lower() == "true"

    app.logger.info(
        f"Starting Flask application on {host}:{port} (debug={debug})"
    )  # Changed to app.logger
    app.run(host=host, port=port, debug=debug)
