from app import create_app, db
from app.models import User
from werkzeug.security import generate_password_hash
import os
import logging
from logging.handlers import RotatingFileHandler
from flask import render_template
from flask_migrate import upgrade
import awsgi

app = create_app()

@app.cli.command("init-db")
def init_db_command():
    """Initialize the database."""
    db.create_all()
    if not User.query.filter_by(is_admin=True).first():
        admin_password = os.getenv('ADMIN_PASSWORD')
        if not admin_password:
            raise ValueError('ADMIN_PASSWORD environment variable is not set')
        admin = User(
            username=os.getenv('ADMIN_USERNAME', 'admin'),
            email=os.getenv('ADMIN_EMAIL'),
            company=os.getenv('ADMIN_COMPANY', 'System Administration'),
            password_hash=generate_password_hash(admin_password),
            is_admin=True
        )
        db.session.add(admin)
        db.session.commit()
    print("Initialized the database.")

# Set up logging
if not app.debug:
    file_handler = RotatingFileHandler('logs/flask_error.log', maxBytes=10240, backupCount=10)
    file_handler.setFormatter(logging.Formatter(
        '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
    ))
    file_handler.setLevel(logging.INFO)
    app.logger.addHandler(file_handler)
    app.logger.setLevel(logging.INFO)
    app.logger.info('Mold Cost Calculator startup')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5004) 

def lambda_handler(event, context):
    return awsgi.response(app, event, context)

def lambda_handler_upgrade_db(event, context):
    with app.app_context():
        upgrade()
    return {"statusCode": 200, "body": "Database upgraded successfully"}