import os
import click
from flask import Flask

def create_app():
    app = Flask(__name__)

    @app.route('/')
    def index():
        return 'Namaste Duniya! This is a Flask app generated by Flask-Wiz.'

    return app

@click.group()
def cli():
    pass

@cli.command()
def new():
    name = click.prompt('Enter project name')

    db_options = ['mongodb', 'sqlite', 'mysql', 'postgresql']
    db = click.prompt('Select database system', type=click.Choice(db_options))

    os.makedirs(name)
    os.chdir(name)

    os.makedirs('templates')
    os.makedirs('static')

    with open('.gitignore', 'w') as gitignore_file:
        gitignore_file.write("# Default .gitignore for Flask project\n")
        gitignore_file.write("venv/\n")
        gitignore_file.write("__pycache__/\n")
        gitignore_file.write(".vscode/\n")

    with open('.env', 'w') as env_file:
        env_file.write("# Default .env file for Flask project\n")

    with open('app.py', 'w') as app_file:
        db_module = None

        if db == 'mongodb':
            db_module = 'pymongo'
            app_file.write(
                """from flask import Flask
from pymongo import MongoClient

app = Flask(__name__)
client = MongoClient('mongodb://localhost:27017/')
db = client['my_database']

@app.route('/')
def index():
    return 'Namaste Duniya! This is a Flask app generated by Flask-Wiz for MongoDB.'

if __name__ == '__main__':
    app.run()
""")
        elif db == 'sqlite':
            db_module = 'sqlite3'
            app_file.write(
                """from flask import Flask
import sqlite3

app = Flask(__name__)
conn = sqlite3.connect('database.db')

@app.route('/')
def index():
    return 'Namaste Duniya! This is a Flask app generated by Flask-Wiz for SQLite.'

if __name__ == '__main__':
    app.run()
""")
        elif db == 'mysql':
            db_module = 'pymysql'
            app_file.write(
                """from flask import Flask
import pymysql

app = Flask(__name__)
conn = pymysql.connect(host='localhost', user='root', password='', database='my_database')

@app.route('/')
def index():
    return 'Namaste Duniya! This is a Flask app generated by Flask-Wiz MySQL.'

if __name__ == '__main__':
    app.run()
""")
        elif db == 'postgresql':
            db_module = 'psycopg2'
            app_file.write(
                """from flask import Flask
import psycopg2

app = Flask(__name__)
conn = psycopg2.connect(host='localhost', user='postgres', password='', dbname='my_database')

@app.route('/')
def index():
    return 'Namaste Duniya! This is a Flask app generated by Flask-Wiz PostgreSQL.'

if __name__ == '__main__':
    app.run()
""")

    if db_module:
        os.system(f"pip install {db_module}")  # Install the required database module

    click.echo(f'New Flask project "{name}" created successfully with {db} database!')

if __name__ == '__main__':
    cli()