from flask import Flask, send_from_directory
from flask_cors import CORS
import os
from database.database import db, init_db

app = Flask(__name__, static_folder='..', static_url_path='')
CORS(app)

# Configure database
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:root@localhost/myapp2'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# Initialize database
db.init_app(app)

# Import and register blueprints
from routes.api import api_bp
app.register_blueprint(api_bp, url_prefix='/api')

# Serve static files (HTML, CSS, JS)
@app.route('/')
def index():
    return send_from_directory('..', 'index.html')

@app.route('/<path:path>')
def serve_static(path):
    return send_from_directory('..', path)

# Initialize DB and start server
if __name__ == '__main__':
    with app.app_context():
        try:
            # Test database connection
            db.engine.connect()
            print('DB connection established.')
            
            # Create tables if they don't exist
            db.create_all()
            
            # Initialize default settings
            from services.settings_service import initialize_default_settings
            initialize_default_settings()
            print('Settings initialized.')
            
            # Start server
            app.run(host='0.0.0.0', port=4000, debug=True)
        except Exception as err:
            print(f'Failed to start: {err}')
