#!/usr/bin/python3
#
# Name: export-cybertalk
# Autors: Aleksandr Shamaraev <shad@altlinux.org>
#         Kirill Unitsaev <fiersik@altlinux.org>
#         Hihin Ruslan <ruslandh@altlinux.org>
# License: AGPL-3.0-or-later
# URL: https://altlinux.space/shad

import asyncio
import os
import sys

from altrepo import ALTRepo, ALTRepoConfig
from pathlib import Path
from datetime import date
from deep_translator import GoogleTranslator, MyMemoryTranslator

_error = "Правильный запуск: export-cybertalk <google|mymemory> <p10|p11|sisyphus|bugs> <--show|--toMD|--toMDshow> <--no-export|--enable-translate>"

home = Path.home()

async def export_cybertalk():

    config = ALTRepoConfig(
        appstream_dir = home / ".cache" / "export-cybertalk" / "appstream",
        appstream_branches=["sisyphus", "p11", "p10"],
    )

    client = ALTRepo(config=config)

    await client.init()
    link = ""
    bugs = False
    new = True
    _toMD = False
    bug_link = "https://bugzilla.altlinux.org/"
    pkg_link ="https://packages.altlinux.org/ru/sisyphus/srpms/"

    if sys.argv[1].strip().lower() == "sisyphus":
        new = False
        news = await client.parser.news.sisyphus()
        link = "https://packages.altlinux.org/ru/sisyphus/srpms/"
    elif sys.argv[1].strip().lower() == "p11":
        new = False
        news = await client.parser.news.p11()
        link = "https://packages.altlinux.org/ru/p11/srpms/"
    elif sys.argv[1].strip().lower() == "p10":
        new = False
        news = await client.parser.news.p10()
        link = "https://packages.altlinux.org/ru/p10/srpms/"
    elif sys.argv[1].strip().lower() == "bugs":
        new = False
        news = await client.parser.news.bugs()
        bugs = True
    elif new:
        if sys.argv[2].strip().lower() == "sisyphus":
            news = await client.parser.news.sisyphus()
            link = "https://packages.altlinux.org/ru/sisyphus/srpms/"
        elif sys.argv[2].strip().lower() == "p11":
            news = await client.parser.news.p11()
            link = "https://packages.altlinux.org/ru/p11/srpms/"
        elif sys.argv[2].strip().lower() == "p10":
            news = await client.parser.news.p10()
            link = "https://packages.altlinux.org/ru/p10/srpms/"
        elif sys.argv[2].strip().lower() == "bugs":
            news = await client.parser.news.bugs()
            bugs = True

    else:
        print("Ошибка запуска.\n" + _error)
        await client.close()
        sys.exit()

    if news:
        if len(sys.argv) > 3:
            _noexport = True if sys.argv[3].strip().lower() == "--no-export" else False
            _enable_translate = True if sys.argv[3].strip().lower() == "--enable-translate" else False
            if (sys.argv[2].strip().lower() == "--show") or (sys.argv[2].strip().lower() == "--tomdshow"):
                _show = True
            else:
                _show = False

            if (sys.argv[2].strip().lower() == "--tomd") or (sys.argv[2].strip().lower() == "--tomdshow"):
                _toMD = True
            else:
                _toMD = False

            if not _show:
                if len(sys.argv) > 3:
                    if (sys.argv[3].strip().lower() == "--show") or (sys.argv[3].strip().lower() == "--tomdshow"):
                        _show = True
                    else:
                        _show = False

                    if (sys.argv[3].strip().lower() == "--tomd") or (sys.argv[3].strip().lower() == "--tomdshow"):
                        _toMD = True
                    else:
                        _toMD = False

            if not _noexport:
                if len(sys.argv) > 4:
                    _noexport = True if sys.argv[4].strip().lower() == "--no-export" else False

            if not _enable_translate:
                if len(sys.argv) > 4:
                    _enable_translate = True if sys.argv[4].strip().lower() == "--enable-translate" else False

        elif len(sys.argv) > 2:
            if (sys.argv[2].strip().lower() == "--show") or (sys.argv[2].strip().lower() == "--tomdshow"):
                _show = True
            else:
                _show =False

            if (sys.argv[2].strip().lower() == "--tomd") or (sys.argv[2].strip().lower() == "--tomdshow"):
                _toMD = True
            else:
                _toMD = False

            _noexport = False
            _enable_translate = False
            if not _show:
                if len(sys.argv) > 3:
                    if (sys.argv[3].strip().lower() == "--show") or (sys.argv[3].strip().lower() == "--tomdshow"):
                        _show = True
                    else:
                        _show = False

                    if (sys.argv[3].strip().lower() == "--tomd") or (sys.argv[3].strip().lower() == "--tomdshow"):
                        _toMD = True
                    else:
                        _toMD = False

        else:
            _show = False
            _noexport = False
            _enable_translate = False

        if not _noexport:
            print("Выгружаю...")

        if not bugs:
            # sorting block - thnx fiersik@ ---
            for filed in ("added", "updated"):
                setattr(
                    news,
                    filed,
                    sorted(
                        getattr(news, filed) or [],
                        key=lambda x: x.maintainer_name,
                    )
                    or None,
                )
        # --------------

        if os.path.exists(home / "export-cybertalk.txt"):
            os.remove(home / "export-cybertalk.txt")

        if os.path.exists(home / "export-cybertalk.md"):
            os.remove(home / "export-cybertalk.md")

        export_file = home / "export-cybertalk.md" if _toMD else home / "export-cybertalk.txt"

        with open(export_file, "w") as __f:
            act_date = "Текущая дата: "+ date.today().strftime('%d-%m-%Y')
            if _show:
                print(act_date)

            if not _noexport:
                __f.write(act_date+"\n")

            if bugs:
                if _show:
                    if _toMD:
                        print(f"# Быстро закрытые: {len(news.quickly_resolved or [])}\n")
                    else:
                        print(f"Быстро закрытые: {len(news.quickly_resolved or [])}\n")

                if not _noexport:
                    if _toMD:
                        __f.write(f"# Быстро закрытые: {len(news.quickly_resolved or [])}\n\n")
                    else:
                        __f.write(f"Быстро закрытые: {len(news.quickly_resolved or [])}\n\n")

                if len(news.quickly_resolved or [])>0:
                    for bug in news.quickly_resolved or []:
                        if _show:
                            if _toMD:
                                print(f"[#{bug.id}]({bug_link}{bug.id}) | [{bug.component}]({pkg_link}{bug.component}) | {bug.priority} | {bug.status}")
                            else:
                                print(f"#{bug.id} ({bug_link}{bug.id}) | {bug.component} | {bug.priority} | {bug.status}")
                            print(f"{bug.summary}\n")

                        if not _noexport:
                            if _toMD:
                                __f.write(f"[#{bug.id}]({bug_link}{bug.id}) | [{bug.component}]({pkg_link}{bug.component}) | {bug.priority} | {bug.status}\n")
                            else:
                                __f.write(f"#{bug.id} ({bug_link}{bug.id}) | {bug.component} | {bug.priority} | {bug.status}\n")
                            __f.write(f"{bug.summary}\n\n")

                if _show:
                    if _toMD:
                        print(f"# Новые баги: {len(news.new or [])}\n")
                    else:
                        print(f"Новые баги: {len(news.new or [])}\n")

                if not _noexport:
                    if _toMD:
                        __f.write(f"# Новые баги: {len(news.new or [])}\n\n")
                    else:
                        __f.write(f"Новые баги: {len(news.new or [])}\n\n")

                if len(news.new or [])>0:
                    for bug in news.new or []:
                        if _show:
                            if _toMD:
                                print(f"[#{bug.id}]({bug_link}{bug.id}) | [{bug.component}]({pkg_link}{bug.component}) | {bug.priority} | {bug.status}")
                            else:
                                print(f"#{bug.id} ({bug_link}{bug.id}) | {bug.component} | {bug.priority} | {bug.status}")
                            print(f"{bug.summary}\n")

                        if not _noexport:
                            if _toMD:
                                __f.write(f"[#{bug.id}]({bug_link}{bug.id}) | [{bug.component}]({pkg_link}{bug.component}) | {bug.priority} | {bug.status}\n")
                            else:
                                __f.write(f"#{bug.id} ({bug_link}{bug.id}) | {bug.component} | {bug.priority} | {bug.status}\n")
                            __f.write(f"{bug.summary}\n\n")

                if _show:
                    if _toMD:
                        print(f"# Баги убранные из ветки Сизифа: {len(news.old or [])}\n")
                    else:
                        print(f"Баги убранные из ветки Сизифа: {len(news.old or [])}\n")

                if not _noexport:
                    if _toMD:
                        __f.write(f"# Баги убранные из ветки Сизифа: {len(news.old or [])}\n\n")
                    else:
                        __f.write(f"Баги убранные из ветки Сизифа: {len(news.old or [])}\n\n")

                if len(news.old or [])>0:
                    for bug in news.old or []:
                        if _show:
                            if _toMD:
                                print(f"[#{bug.id}]({bug_link}{bug.id}) | [{bug.component}]({pkg_link}{bug.component}) | {bug.priority} | {bug.status}")
                            else:
                                print(f"#{bug.id} ({bug_link}{bug.id}) | {bug.component} | {bug.priority} | {bug.status}")
                            print(f"{bug.summary}\n")

                        if not _noexport:
                            if _toMD:
                                __f.write(f"[#{bug.id}]({bug_link}{bug.id}) | [{bug.component}]({pkg_link}{bug.component}) | {bug.priority} | {bug.status}\n")
                            else:
                                __f.write(f"#{bug.id} ({bug_link}{bug.id}) | {bug.component} | {bug.priority} | {bug.status}\n")
                            __f.write(f"{bug.summary}\n\n")

                if _show:
                    if _toMD:
                        print(f"# Закрытые баги: {len(news.resolved or [])}\n")
                    else:
                        print(f"Закрытые баги: {len(news.resolved or [])}\n")

                if not _noexport:
                    if _toMD:
                        __f.write(f"# Закрытые баги: {len(news.resolved or [])}\n\n")
                    else:
                        __f.write(f"Закрытые баги: {len(news.resolved or [])}\n\n")

                if len(news.resolved or [])>0:
                    for bug in news.resolved or []:
                        if _show:
                            if _toMD:
                                print(f"[#{bug.id}]({bug_link}{bug.id}) | [{bug.component}]({pkg_link}{bug.component}) | {bug.priority} | {bug.status}")
                            else:
                                print(f"#{bug.id} ({bug_link}{bug.id}) | {bug.component} | {bug.priority} | {bug.status}")
                            print(f"{bug.summary}\n")

                        if not _noexport:
                            if _toMD:
                                __f.write(f"[#{bug.id}]({bug_link}{bug.id}) | [{bug.component}]({pkg_link}{bug.component}) | {bug.priority} | {bug.status}\n")
                            else:
                                __f.write(f"#{bug.id} ({bug_link}{bug.id}) | {bug.component} | {bug.priority} | {bug.status}\n")
                            __f.write(f"{bug.summary}\n\n")

                if _show:
                    if _toMD:
                        print(f"# Переоткрытые баги: {len(news.reopened or [])}\n")
                    else:
                        print(f"Переоткрытые баги: {len(news.reopened or [])}\n")

                if not _noexport:
                    if _toMD:
                        __f.write(f"# Переоткрытые баги: {len(news.reopened or [])}\n\n")
                    else:
                        __f.write(f"Переоткрытые баги: {len(news.reopened or [])}\n\n")

                if len(news.reopened or [])>0:
                    for bug in news.reopened or []:
                        if _show:
                            if _toMD:
                                print(f"[#{bug.id}]({bug_link}{bug.id}) | [{bug.component}]({pkg_link}{bug.component}) | {bug.priority} | {bug.status}")
                            else:
                                print(f"#{bug.id} ({bug_link}{bug.id}) | {bug.component} | {bug.priority} | {bug.status}")
                            print(f"{bug.summary}\n")

                        if not _noexport:
                            if _toMD:
                                __f.write(f"[#{bug.id}]({bug_link}{bug.id}) | [{bug.component}]({pkg_link}{bug.component}) | {bug.priority} | {bug.status}\n")
                            else:
                                __f.write(f"#{bug.id} ({bug_link}{bug.id}) | {bug.component} | {bug.priority} | {bug.status}\n")
                            __f.write(f"{bug.summary}\n\n")

                if _show:
                    if _toMD:
                        print(f"# Случайная подборка багов: {len(news.random or [])}\n")
                    else:
                        print(f"Случайная подборка багов: {len(news.random or [])}\n")

                if not _noexport:
                    if _toMD:
                        __f.write(f"# Случайная подборка багов: {len(news.random or [])}\n\n")
                    else:
                        __f.write(f"Случайная подборка багов: {len(news.random or [])}\n\n")

                if len(news.random or [])>0:
                    for bug in news.random or []:
                        if _show:
                            if _toMD:
                                print(f"[#{bug.id}]({bug_link}{bug.id}) | [{bug.component}]({pkg_link}{bug.component}) | {bug.priority} | {bug.status}")
                            else:
                                print(f"#{bug.id} ({bug_link}{bug.id}) | {bug.component} | {bug.priority} | {bug.status}")
                            print(f"{bug.summary}\n")

                        if not _noexport:
                            if _toMD:
                                __f.write(f"[#{bug.id}]({bug_link}{bug.id}) | [{bug.component}]({pkg_link}{bug.component}) | {bug.priority} | {bug.status}\n")
                            else:
                                __f.write(f"#{bug.id} ({bug_link}{bug.id}) | {bug.component} | {bug.priority} | {bug.status}\n")
                            __f.write(f"{bug.summary}\n\n")

                if _show:
                    if _toMD:
                        print(f"Источник [sisyphus-cybertalk]({news.url})\n")
                    else:
                        print(f"Источник sisyphus-cybertalk: {news.url}\n")
                if not _noexport:
                    if _toMD:
                        __f.write(f"Источник [sisyphus-cybertalk]({news.url})\n")
                    else:
                        __f.write(f"Источник sisyphus-cybertalk: {news.url}\n\n")

            else:
                flagcount = True
                if sys.argv[1].strip().lower() == "google":
                    translated = GoogleTranslator(source="auto", target="ru")
                elif sys.argv[1].strip().lower() == "mymemory":
                    translated = MyMemoryTranslator(source='english', target='russian')
                else:
                    translated = MyMemoryTranslator(source='english', target='russian')

                if _show:
                    if _toMD:
                        print(f"# Добавлено: {len(news.added or [])}\n")
                    else:
                        print(f"Добавлено: {len(news.added or [])}\n")

                if not _noexport:
                    if _toMD:
                        __f.write(f"# Добавлено: {len(news.added or [])}\n\n")
                    else:
                        __f.write(f"Добавлено: {len(news.added or [])}\n\n")

                for pkg in news.added or []:

                    if flagcount:
                        maintainer_name = pkg

                    if maintainer_name.maintainer_name != pkg.maintainer_name:

                        if _show:
                            print(f"{maintainer_name.maintainer_name} ({maintainer_name.maintainer_nick})\n")

                        if not _noexport:
                            __f.write(f"{maintainer_name.maintainer_name} ({maintainer_name.maintainer_nick})\n\n")

                    if _enable_translate:
                        perevod = translated.translate(pkg.description)
                    else:
                        perevod = pkg.description

                    if _show:
                        if _toMD:
                            print(f"[{pkg.name}]({link+pkg.name}) - {perevod}\n")
                        else:
                            print(f"{pkg.name} ({link}{pkg.name}) - {perevod}\n")

                    if not _noexport:
                        if _toMD:
                            __f.write(f"[{pkg.name}]({link+pkg.name}) - {perevod}\n")
                        else:
                            __f.write(f"{pkg.name} ({link}{pkg.name}) - {perevod}\n")

                    if flagcount:
                        flagcount = False

                    maintainer_name = pkg

                if len(news.added or []) > 0:

                    if _show:
                        print(f"{pkg.maintainer_name} ({pkg.maintainer_nick})\n")

                    if not _noexport:
                        __f.write(f"{pkg.maintainer_name} ({pkg.maintainer_nick})\n\n")

                if _show:
                    if _toMD:
                        print(f"\n# Удалено: {len(news.removed or [])}\n")
                    else:
                        print(f"\nУдалено: {len(news.removed or [])}\n")

                if not _noexport:
                    if _toMD:
                        __f.write(f"\n# Удалено: {len(news.removed or [])}\n\n")
                    else:
                        __f.write(f"\nУдалено: {len(news.removed or [])}\n\n")

                for pkg in news.removed or []:

                    if _show:
                        if _toMD:
                            print(f"[{pkg.name}]({link+pkg.name})\n")
                        else:
                            print(f"{pkg.name} ({link}{pkg.name})\n")

                    if not _noexport:
                        if _toMD:
                            __f.write(f"[{pkg.name}]({link+pkg.name})\n")
                        else:
                            __f.write(f"{pkg.name} ({link}{pkg.name})\n")

                flagcount = True

                if _show:
                    if _toMD:
                        print(f"\n# Обновлено: {len(news.updated or [])}\n")
                    else:
                        print(f"\nОбновлено: {len(news.updated or [])}\n")

                if not _noexport:
                    if _toMD:
                        __f.write(f"\n# Обновлено: {len(news.updated or [])}\n\n")
                    else:
                        __f.write(f"\nОбновлено: {len(news.updated or [])}\n\n")

                for pkg in news.updated or []:

                    if flagcount:
                        maintainer_name = pkg

                    if maintainer_name.maintainer_name != pkg.maintainer_name:

                        if _show:
                            print(f"{maintainer_name.maintainer_name} ({maintainer_name.maintainer_nick})\n")

                        if not _noexport:
                            __f.write(f"{maintainer_name.maintainer_name} ({maintainer_name.maintainer_nick})\n\n")

                    if _enable_translate:
                        perevod = translated.translate(pkg.description)
                    else:
                        perevod = pkg.description

                    if _show:
                        if _toMD:
                            print(f"[{pkg.name}]({link+pkg.name}) - {perevod}\n")
                        else:
                            print(f"{pkg.name} ({link}{pkg.name}) - {perevod}\n")

                    if not _noexport:
                        if _toMD:
                            __f.write(f"[{pkg.name}]({link+pkg.name}) - {perevod}\n")
                        else:
                            __f.write(f"{pkg.name} ({link}{pkg.name}) - {perevod}\n")

                    if flagcount:
                        flagcount = False

                    maintainer_name = pkg

                if len(news.updated or []) > 0:

                    if _show:
                        print(f"{pkg.maintainer_name} ({pkg.maintainer_nick})\n")

                    if not _noexport:
                        __f.write(f"{pkg.maintainer_name} ({pkg.maintainer_nick})\n\n")

                if _show:
                    if _toMD:
                        print(f"\n# Всего: {news.total}\n")
                        print(f"## Источник [sisyphus-cybertalk]({news.url})\n")
                    else:
                        print(f"\nВсего: {news.total}\n")
                        print(f"Источник sisyphus-cybertalk: {news.url}\n")

                if not _noexport:
                    if _toMD:
                        __f.write(f"\n# Всего: {news.total}\n")
                        __f.write(f"## Источник [sisyphus-cybertalk]({news.url})\n")
                    else:
                        __f.write(f"\nВсего: {news.total}\n\n")
                        __f.write(f"Источник sisyphus-cybertalk: {news.url}\n\n")

            if not _noexport:
                if _toMD:
                    print(f"Выгружено в - {home}/export-cybertalk.md")
                else:
                    print(f"Выгружено в - {home}/export-cybertalk.txt")

    else:
        print("Новостей нет")
    await client.close()

if len(sys.argv) > 1:
    asyncio.run(export_cybertalk())
else:
    print(_error)
