import typer
import uvicorn
from sqlmodel import Session, select

from .app import app
from .config import settings
from .db import create_db_and_tables, engine
from .models.content import Content
from .security import User

cli = typer.Typer(name="pythontasks API")


@cli.command()
def run(
    port: int = settings.server.port,
    host: str = settings.server.host,
    log_level: str = settings.server.log_level,
    reload: bool = settings.server.reload,
):  # pragma: no cover
    """Run the API server."""
    uvicorn.run(
        "pythontasks.app:app",
        host=host,
        port=port,
        log_level=log_level,
        reload=reload,
    )


@cli.command()
def create_user(username: str, password: str, superuser: bool = False):
    """Create user"""
    create_db_and_tables(engine)
    with Session(engine) as session:
        user = User(username=username, password=password, superuser=superuser)
        session.add(user)
        session.commit()
        session.refresh(user)
        typer.echo(f"created {username} user")
        return user


@cli.command()
def shell():  # pragma: no cover
    """Opens an interactive shell with objects auto imported"""
    _vars = {
        "app": app,
        "settings": settings,
        "User": User,
        "engine": engine,
        "cli": cli,
        "create_user": create_user,
        "select": select,
        "session": Session(engine),
        "Content": Content,
    }
    typer.echo(f"Auto imports: {list(_vars.keys())}")
    try:
        from IPython import start_ipython

        start_ipython(argv=[], user_ns=_vars)
    except ImportError:
        import code

        code.InteractiveConsole(_vars).interact()

typer.echo sqlmodel.Session typer.Typer IPython.start_ipython uvicorn.run code.InteractiveConsole
[((231, 266), 'typer.Typer', 'typer.Typer', ([], {'name': '"""pythontasks API"""'}), "(name='pythontasks API')\n", (242, 266), False, 'import typer\n'), ((517, 614), 'uvicorn.run', 'uvicorn.run', (['"""pythontasks.app:app"""'], {'host': 'host', 'port': 'port', 'log_level': 'log_level', 'reload': 'reload'}), "('pythontasks.app:app', host=host, port=port, log_level=\n    log_level, reload=reload)\n", (528, 614), False, 'import uvicorn\n'), ((810, 825), 'sqlmodel.Session', 'Session', (['engine'], {}), '(engine)\n', (817, 825), False, 'from sqlmodel import Session, select\n'), ((1006, 1044), 'typer.echo', 'typer.echo', (['f"""created {username} user"""'], {}), "(f'created {username} user')\n", (1016, 1044), False, 'import typer\n'), ((1392, 1407), 'sqlmodel.Session', 'Session', (['engine'], {}), '(engine)\n', (1399, 1407), False, 'from sqlmodel import Session, select\n'), ((1557, 1594), 'IPython.start_ipython', 'start_ipython', ([], {'argv': '[]', 'user_ns': '_vars'}), '(argv=[], user_ns=_vars)\n', (1570, 1594), False, 'from IPython import start_ipython\n'), ((1648, 1678), 'code.InteractiveConsole', 'code.InteractiveConsole', (['_vars'], {}), '(_vars)\n', (1671, 1678), False, 'import code\n')]