import os
import click
import subprocess
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

db_options = {'1': 'mongodb', '2': 'sqlite3', '3': 'mysql', '4': 'postgresql'}
frontend_options = {'1': 'React', '2': 'VueJs', '3': 'NextJs', '4': 'Angular'}
value_key = {v: k for k, v in db_options.items()}

def display_options(options):
    return "\n".join([f"{key}: {value}" for key, value in options.items()])

def create_app():
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
    db.init_app(app)
    return app

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

@cli.command()
def new():
    while True:
        name = click.prompt('Enter project name')
        if os.path.exists(name):
            click.echo(f"Project {name} already exists. Choose another name.")
        else:
            break
    
    frontend_choice = click.confirm("Do you need a frontend framework?")
    if frontend_choice:
        click.echo("Select a frontend framework:")
        click.echo(display_options(frontend_options))
        while True:
            frontend_input = click.prompt("Enter frontend framework")
            if frontend_input in frontend_options:
                frontend_framework = frontend_options[frontend_input]
                break
            elif frontend_input in frontend_options.values():
                frontend_framework = frontend_input
                break
            else:
                click.echo("Invalid input. Choose a valid frontend framework.")
    else:
        frontend_framework = None
    
    click.echo("Select a database system:")
    click.echo(display_options(db_options))
    
    while True:
        db_input = click.prompt("Enter database selection")
        if db_input in db_options:
            db_key = db_input
            break
        elif db_input in value_key:
            db_key = value_key[db_input]
            break
        else:
            click.echo("Invalid input. Choose a valid database.")
    
    os.makedirs(name)
    os.chdir(name)
    
    # Create server directory and setup backend
    os.makedirs('server')
    os.chdir('server')
    os.makedirs('templates')
    os.makedirs('static')
    
    db_module = None
    db_uri = ""
    if db_key == '1':
        db_module = 'pymongo'
        db_uri = "'mongodb://localhost:27017/my_database'"
    elif db_key == '2':
        db_module = 'sqlite3'
        db_uri = "'sqlite:///database.db'"
    elif db_key == '3':
        db_module = 'pymysql'
        db_uri = "'mysql+pymysql://root:password@localhost/my_database'"
    elif db_key == '4':
        db_module = 'psycopg2-binary'
        db_uri = "'postgresql://postgres:password@localhost/my_database'"
    
    with open('app.py', 'w') as app_file:
        app_file.write(f"""
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
import os

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = {db_uri}
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)
migrate = Migrate(app, db)

@app.route('/')
def index():
    return render_template('home.html', message='Namaste Duniya! This is a Flask app generated by Flask-Wiz.')

if __name__ == '__main__':
    app.run()
""")
    
    with open('requirements.txt', 'w') as req_file:
        req_file.write("flask\nflask_sqlalchemy\nflask_migrate\ngunicorn\n")
        if db_module and db_module != 'sqlite3':
            req_file.write(f"{db_module}\n")
    
    os.chdir('..')



    if frontend_framework:
        os.makedirs('client')
        os.chdir('client')
        click.echo(f"Setting up {frontend_framework}...")
        if frontend_framework == 'React':
            os.system("npm create vite@latest . -- --template react")
        elif frontend_framework == 'VueJs':
            os.system("npm create vite@latest . -- --template vue")
        elif frontend_framework == 'nextjs':
            os.system("npx create-next-app@latest .")
        elif frontend_framework == 'Angular':
            os.system("ng new my-angular-vite-app")
        click.echo(f"{frontend_framework} setup completed!")
    
    click.echo(f'New project "{name}" created successfully!')

if __name__ == '__main__':
    cli()