# Validate configuration before starting the app
from functions.validate_config import validate_config
from functions.secret_key import get_secret_key
from config import item_attributes, sql_conf

config_status = validate_config(item_attributes)
if config_status != "Ok":
    raise SystemExit(f"Configuration Error: {config_status}")

# Import flask and sql to start the app
from flask import Flask, redirect
from sqlalchemy import exc
from definitions.models import *

# Import the Blueprints
from routes.homepage import homepage_bp
from routes.viewall import viewall_bp
from routes.export_csv import export_csv_bp
from routes.create import addasset_bp
from routes.update import update_bp
from routes.delete import delete_bp
from routes.upload import upload_bp
from routes.confirm_save import confirm_save_bp

app = Flask(__name__)
app.secret_key = get_secret_key()  # Required for flashing messages and session
app.config['SQLALCHEMY_DATABASE_URI'] = f'mysql://{sql_conf.SQL_USER}:{sql_conf.SQL_PASSWORD}@{sql_conf.SQL_HOST}/{sql_conf.SQL_DB}'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)

# Register the Blueprints
app.register_blueprint(homepage_bp)
app.register_blueprint(viewall_bp)
app.register_blueprint(export_csv_bp)
app.register_blueprint(addasset_bp)
app.register_blueprint(update_bp)
app.register_blueprint(delete_bp)
app.register_blueprint(upload_bp)
app.register_blueprint(confirm_save_bp)

# Create database table if it doesn't exist
with app.app_context():
    try:
        db.create_all()
    except exc.SQLAlchemyError as e:
        # Log the error and exit gracefully
        print(f"Database Error: Failed to create tables. {str(e)}")
        raise SystemExit("Database connection failed. Please check your configuration.")

if __name__ == '__main__':
    app.run(host='localhost', port=5000)
