import click
import uvloop
from aiohttp import web
import asyncio
from snek.app import Application
from IPython import start_ipython
import sqlite3
import pathlib
import shutil 

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

@cli.command()
@click.option('--db_path',default="snek.db", help='Database to initialize if not exists.')
@click.option('--source',default=None, help='Database to initialize if not exists.')
def init(db_path,source):
    if source and pathlib.Path(source).exists():
        print(f"Copying {source} to {db_path}")
        shutil.copy2(source,db_path)
        print("Database initialized.")
        return
 
    if pathlib.Path(db_path).exists():
        return
    print(f"Initializing database at {db_path}")
    db = sqlite3.connect(db_path)
    db.cursor().executescript(
        pathlib.Path(__file__).parent.joinpath("schema.sql").read_text()
    )
    db.commit()
    db.close()
    print("Database initialized.")

@cli.command()
@click.option('--port', default=8081, show_default=True, help='Port to run the application on')
@click.option('--host', default='0.0.0.0', show_default=True, help='Host to run the application on')
@click.option('--db_path', default='snek.db', show_default=True, help='Database path for the application')
def serve(port, host, db_path):
    #init(db_path)
    #asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
    web.run_app(
        Application(db_path=f"sqlite:///{db_path}"), port=port, host=host
    )

@cli.command()
@click.option('--db_path', default='snek.db', show_default=True, help='Database path for the application')
def shell(db_path):
    app = Application(db_path=f"sqlite:///{db_path}")
    start_ipython(argv=[], user_ns={'app': app})

def main():
    cli()

if __name__ == "__main__":
    main()
