# -*- coding: utf-8 -*-
# type: ignore
from __future__ import annotations

import re

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

from hotpocket_workspace_tools import get_workspace_mode
import hotpocket_workspace_tools.tasks

WORKSPACE_MODE = get_workspace_mode()


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


@task
def test(ctx: Context):
    print('NOOP')


@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):
    print('NOOP')


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

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

    try:
        isort(ctx, check=True)
    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):
    raise NotImplementedError()


@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):
    print('NOOP')


@task
def start_web(ctx: Context):
    raise NotImplementedError()


@task
def bump_version(ctx: Context, next_version: str, build: str | None = None):
    hotpocket_workspace_tools.tasks.utils.bump_version(
        ctx, next_version, build=build,
    )

    pbxproj_content = None
    with open('HotPocket.xcodeproj/project.pbxproj', 'r', encoding='utf-8') as pbxproj_content_f:
        pbxproj_content = pbxproj_content_f.read()

    pbxproj_content = re.sub(
        r'CURRENT_PROJECT_VERSION = [0-9]{10};',
        f'CURRENT_PROJECT_VERSION = {build};',
        pbxproj_content,
        flags=re.MULTILINE,
    )

    with open('HotPocket.xcodeproj/project.pbxproj', 'w', encoding='utf-8') as pbxproj_content_f:
        pbxproj_content_f.write(pbxproj_content)
