from flask import Flask
from extensions import db, migrate, login_manager
from dotenv import load_dotenv
import os

load_dotenv()

def create_app():
  app = Flask(__name__)

  app.config['SQLALCHEMY_DATABASE_URI'] = (
      f"mysql+pymysql://{os.getenv('DB_USER')}:{os.getenv('DB_PASSWORD')}"
      f"@{os.getenv('DB_HOST')}:{os.getenv('DB_PORT')}/{os.getenv('DB_NAME')}"
  )
  app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
  app.config['SECRET_KEY'] = os.getenv('SECRET_KEY', 'devsecret')
  app.config['UPLOAD_FOLDER'] = 'static/uploads'
  app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
  app.config['ALLOWED_EXTENSIONS'] = {'png', 'jpg', 'jpeg', 'gif'}

  os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
  db.init_app(app)
  migrate.init_app(app, db)
  login_manager.init_app(app)
  login_manager.login_view = 'auth.login'
  @login_manager.user_loader
  def load_user(user_id):
    from models import User
    return User.query.get(int(user_id))

  from models import User, Product, Category, Cart, CartItem, Order, OrderItem
  from routes.main import main_bp
  from routes.cart import cart_bp
  from routes.auth import auth_bp
  from routes.admin import admin_bp
  from routes.user import user_bp

  app.register_blueprint(main_bp)
  app.register_blueprint(cart_bp)
  app.register_blueprint(auth_bp)
  app.register_blueprint(admin_bp)
  app.register_blueprint(user_bp)

  return app

if __name__ == '__main__':
  app = create_app()
  app.run(host='0.0.0.0', port=5000, debug=True)
