# -*- coding: utf-8 -*-
# type: ignore

from __future__ import annotations

import os

from invoke import Context, task
from invoke.exceptions import UnexpectedExit

from hotpocket_workspace_tools import WorkspaceMode, get_workspace_mode
from hotpocket_workspace_tools.tasks import *  # noqa: F401,F403

WORKSPACE_MODE = get_workspace_mode()
ENV = os.getenv('HOTPOCKET_BACKEND_ENV', 'docker')


@task
def clean(ctx: Context):
    ctx.run('rm -rf hotpocket_backend/static/')


@task
def test(ctx: Context):
    ctx.run('pytest -v --disable-warnings')


@task
def flake8(ctx: Context):
    ctx.run('flake8')


@task
def isort(ctx: Context, check=False, diff=False):
    command_parts = [
        'isort',
    ]

    if check is True:
        command_parts.append('--check')

    if diff is True:
        command_parts.append('--diff')

    command_parts.append('.')

    ctx.run(' '.join(command_parts))


@task
def eslint(ctx: Context):
    ctx.run('yarn run eslint')


@task
def lint(ctx: Context):
    ihazsuccess = True

    try:
        flake8(ctx)
    except UnexpectedExit:
        ihazsuccess = False

    try:
        isort(ctx, check=True)
    except UnexpectedExit:
        ihazsuccess = False

    try:
        eslint(ctx)
    except UnexpectedExit:
        ihazsuccess = False

    if ihazsuccess is False:
        raise RuntimeError('FIAL')


@task
def typecheck(ctx: Context):
    ctx.run('mypy .')


@task
def django_shell(ctx: Context):
    ctx.run('python manage.py shell_plus')


@task
def ci(ctx: Context):
    ihazsuccess = True

    ci_tasks = [test, lint, typecheck]
    for ci_task in ci_tasks:
        try:
            ci_task(ctx)
        except UnexpectedExit:
            ihazsuccess = False

    if ihazsuccess is False:
        raise RuntimeError('FIAL')


@task
def setup(ctx: Context):
    ctx.run('python manage.py migrate')
    ctx.run('python manage.py create_initial_account -u hotpocket -p hotpocketm4st3r')

    if WORKSPACE_MODE == WorkspaceMode.METAL:
        ctx.run('mkdir -p run/uploads')


@task
def start_web(ctx: Context):
    bind = os.getenv('HOTPOCKET_BACKEND_RUNSERVER_BIND_WEB', '127.0.0.1:8001')
    ctx.run(f'python manage.py runserver {bind}')


@task
def start_admin(ctx: Context):
    bind = os.getenv('HOTPOCKET_BACKEND_RUNSERVER_BIND_ADMIN', '127.0.0.1:8002')
    ctx.run(f'python manage.py runserver {bind}', env=dict(
        DJANGO_SETTINGS_MODULE=f'hotpocket_backend.settings.{ENV}.admin',
        HOTPOCKET_BACKEND_APP='admin',
    ))


@task
def start_celery_worker(ctx: Context, concurrency=2):
    command_parts = [
        'celery',
        '-A hotpocket_backend.celery:app',
        'worker',
        '-l INFO',
        '-Q celery,webapp',
        f'-c {concurrency}',
    ]
    ctx.run(' '.join(command_parts))


@task
def start_celery_beat(ctx: Context, schedule_path='run/celery-beat-schedule'):
    ctx.run(f'celery -A hotpocket_backend.celery:app beat -l INFO -s {schedule_path}')
