from typing import NamedTuple, Literal, Union, Sequence
import vh3


class BuildArcadiaProjectOutput(NamedTuple):
    arcadia_project: vh3.Executable
    sandbox_task_id: vh3.Text


@vh3.decorator.external_operation("https://nirvana.yandex-team.ru/operation/dd4b5735-1ee7-497d-91fc-b81ba8b510fc")
@vh3.decorator.nirvana_output_names(arcadia_project="ARCADIA_PROJECT", sandbox_task_id="SANDBOX_TASK_ID")
def build_arcadia_project(
    *,
    targets: vh3.String,
    arts: vh3.String,
    arcadia_url: vh3.String = "arcadia:/arc/trunk/arcadia",
    arcadia_revision: vh3.Integer = None,
    checkout_arcadia_from_url: vh3.String = None,
    build_type: vh3.Enum[
        Literal["release", "debug", "profile", "coverage", "relwithdebinfo", "valgrind", "valgrind-release"]
    ] = "release",
    arts_source: vh3.String = None,
    result_single_file: vh3.Boolean = False,
    definition_flags: vh3.String = None,
    sandbox_oauth_token: vh3.Secret = None,
    arcadia_patch: vh3.String = None,
    owner: vh3.String = None,
    use_aapi_fuse: vh3.Boolean = True,
    use_arc_instead_of_aapi: vh3.Boolean = True,
    aapi_fallback: vh3.Boolean = False,
    kill_timeout: vh3.Integer = None,
    sandbox_requirements_disk: vh3.Integer = None,
    sandbox_requirements_ram: vh3.Integer = None,
    sandbox_requirements_platform: vh3.Enum[
        Literal[
            "Any",
            "darwin-20.4.0-x86_64-i386-64bit",
            "linux",
            "linux_ubuntu_10.04_lucid",
            "linux_ubuntu_12.04_precise",
            "linux_ubuntu_14.04_trusty",
            "linux_ubuntu_16.04_xenial",
            "linux_ubuntu_18.04_bionic",
            "osx",
            "osx_10.12_sierra",
            "osx_10.13_high_sierra",
            "osx_10.14_mojave",
            "osx_10.15_catalina",
            "osx_10.16_big_sur",
        ]
    ] = None,
    checkout: vh3.Boolean = False,
    clear_build: vh3.Boolean = True,
    strip_binaries: vh3.Boolean = False,
    lto: vh3.Boolean = False,
    thinlto: vh3.Boolean = False,
    musl: vh3.Boolean = False,
    use_system_python: vh3.Boolean = False,
    target_platform_flags: vh3.String = None,
    javac_options: vh3.String = None,
    ya_yt_proxy: vh3.String = None,
    ya_yt_dir: vh3.String = None,
    ya_yt_token_vault_owner: vh3.String = None,
    ya_yt_token_vault_name: vh3.String = None,
    result_rt: vh3.String = None,
    timestamp: vh3.Date = None,
    build_system: vh3.Enum[Literal["ya", "ya_force", "semi_distbuild", "distbuild"]] = "ya"
) -> BuildArcadiaProjectOutput:
    """
    Build Arcadia Project
    Launches YA_MAKE task in Sandbox for provided target and downloads requested artifact.
    :param targets: Target
      [[Multiple targets with ";" are not allowed]]
    :param arts: Build artifact
      [[Multiple artifacts with ";" and custom destination directory with "=" are not allowed]]
    :param arcadia_url: Svn url for arcadia
      [[Should not contain revision]]
    :param arcadia_revision: Arcadia Revision
    :param checkout_arcadia_from_url: Full SVN url for arcadia (Overwrites base URL and revision, use @revision to fix revision)
    :param build_type: Build type
    :param arts_source: Source artifacts (semicolon separated pairs path[=destdir])
      [[Какие файлы из Аркадии поместить в отдельный ресурс (формат тот же, что и у build artifacts)]]
    :param result_single_file: Result is a single file
    :param definition_flags: Definition flags
      [[For example "-Dkey1=val1 ... -DkeyN=valN"]]
    :param sandbox_oauth_token: Sandbox OAuth token
      [[To run task on behalf of specific user]]
      Name of the secret containing oauth token of user the sandbox task should be launched from
    :param arcadia_patch: Apply patch
      [[Diff file rbtorrent, paste.y-t.ru link or plain text. Doc: https://nda.ya.ru/3QTTV4]]
    :param owner: Custom sandbox task owner (should be used only with OAuth token)
      [[OAuth token owner should be a member of sandbox group]]
    :param use_aapi_fuse: Use arcadia-api fuse
    :param use_arc_instead_of_aapi: Use arc fuse instead of aapi
    :param aapi_fallback: Fallback to svn/hg if AAPI services are temporary unavailable
    :param kill_timeout: Kill Timeout (seconds)
    :param sandbox_requirements_disk: Disk requirements in Mb
    :param sandbox_requirements_ram: RAM requirements in Mb
    :param sandbox_requirements_platform: Platform
    :param checkout: Run ya make with --checkout
    :param clear_build: Clear build
    :param strip_binaries: Strip result binaries
    :param lto: Build with LTO
    :param thinlto: Build with ThinLTO
    :param musl: Build with musl-libc
    :param use_system_python: Use system Python to build python libraries
    :param target_platform_flags: Target platform flags (only for cross-compilation)
    :param javac_options: Javac options (semicolon separated)
    :param ya_yt_proxy: YT store proxy
    :param ya_yt_dir: YT store cypress path
    :param ya_yt_token_vault_owner: YT token vault owner
    :param ya_yt_token_vault_name: YT token vault name
    :param result_rt: Result resource type
    :param timestamp: Timestamp
    :param build_system: Build System
    """
    raise NotImplementedError("Write your local execution stub here")


class SvnExportSingleFileDeterministicOutput(NamedTuple):
    text: vh3.Text
    json: vh3.JSON
    binary: vh3.Binary
    executable: vh3.Executable
    tsv: vh3.TSV
    file: vh3.File
    html: vh3.HTML
    revision: vh3.Text


@vh3.decorator.external_operation("https://nirvana.yandex-team.ru/operation/940e9ba8-11a0-4daa-ae23-8bf71f11e04c")
def svn_export_single_file_deterministic(
    *,
    arcadia_path: Union[vh3.String, vh3.Text] = None,
    revision: vh3.Integer = None,
    path_prefix: vh3.String = None,
    only_info: vh3.Boolean = False,
    timestamp: vh3.Date = None
) -> SvnExportSingleFileDeterministicOutput:
    """
    SVN: Export single file (Deterministic)

    **Назначение операции**

    Позволяет скачать один файл из SVN-репозитория. В опциях укажите относительный путь в Arcadia и номер ревизии.
    Операция детерминированная. При повторных запусках с теми же параметрами используется кэш. Бинарный файл не будет пересобран, если он уже есть в кэше.

    **Описание входов**

     - arcadia_path — Относительный путь в Arcadia для checkout'а файла, например `arcadia/entity/ugc/tools/nirvana/takeout/main.yql`
      Если выход не указан, значение берется из options.


    **Описание выходов**

     - text, json, binary, executable, tsv, file — возможные форматы файлов для checkout'а.
     - revision — номер ревизии из опции .


    **Ограничения**

    Не предусмотрены.

    :param arcadia_path: Arcadia path
      Относительный путь в аркадии для checkout'а.
    :param arcadia_path:
      Относительный путь в аркадии для checkout'а. Если не указано - берется из options.
    :param revision: Revision
      [[Revision(HEAD if not set)]]
      Revision(HEAD if not set)
    :param path_prefix: Path prefix
      Path prefix to support branches and tags(i.e. https://arcadia.yandex.ru/arc/branches/remorph/stable-1/arcadia/), set to null if trunk
    :param only_info: Only Revision
      Only revision in output(do not export file)
    :param timestamp: Timestamp
      ts for caching
    """
    raise NotImplementedError("Write your local execution stub here")


class SvnCheckoutDeterministicOutput(NamedTuple):
    archive: vh3.Binary
    revision: vh3.Text


@vh3.decorator.external_operation("https://nirvana.yandex-team.ru/operation/15c7eab1-aaf1-49ad-b196-beaa9a8cf3ab")
@vh3.decorator.nirvana_names(ignore_externals="ignore-externals", ignore_missing_path="ignore-missing-path")
def svn_checkout_deterministic(
    *,
    arcadia_path: Union[vh3.String, vh3.Text] = None,
    revision: vh3.Integer = None,
    depth: vh3.Enum[Literal["infinity", "immediates", "files", "empty"]] = "infinity",
    ignore_externals: vh3.Boolean = False,
    path_prefix: vh3.String = None,
    timestamp: vh3.Date = None,
    only_info: vh3.Boolean = False,
    ignore_missing_path: vh3.Boolean = False,
    batch_input: vh3.JSON = None
) -> SvnCheckoutDeterministicOutput:
    """
    SVN: Checkout (Deterministic)

    **Назначение операции**

    Загружает из SVN  содержимое директории по указанному пути и ревизии.
    Для массовой загрузки из разных источников используйте batch-режим, для этого на вход `batch_input` подайте JSON в специальном формате*.
    Операция детерминированная. При повторных запусках с теми же параметрами используется кэш. Бинарный файл не будет пересобран, если он уже есть в кэше.

    **Описание входов**

    Способы передачи пути:
      - через опцию `Arcadia path`;
      - через вход `arcadia_path`.

    Если одновременно указаны опция и вход, будет использовано значение, взятое из входа.


    *Специальный формат JSON для `batch_input`:

    ```
    {
      "batch": [
        {
          "path": "{(required) arcadia relative path like `arcadia/yweb/...`}",
          "rev": {(required) integer revision}
        }
      ]
    }
    ```

    **Описание выходов**

    - `archive` — архив с содержимым запрошенной директории.

    - `revision` — дополнительный выход, содержит ревизию, из которой был сделан checkout (выход полезен, если не указана опция `Revision` и используется HEAD).


    **Ограничения**

     В batch-режиме игнорируются все опции, кроме `Depth`, `Ignore Externals` и `Ignore missing paths in batch mode`.

    :param arcadia_path: Arcadia path
      [[Относительный путь в аркадии для checkout'а. (arcadia/my/project/path)]]
      Относительный путь в аркадии для checkout'а. (arcadia/my/project/path)
    :param arcadia_path:
      Относительный путь в аркадии для checkout'а. Если не указано - берется из options.
    :param revision: Revision(HEAD if not set)
      Ревизия checkout'а.
    :param depth: Depth:
      [[Limit operation by depth ARG ('empty', 'files', 'immediates', or 'infinity')]]
    :param ignore_externals: Ignore Externals:
      [[Ignore externals definitions]]
    :param path_prefix: Path prefix
      Path prefix to support branches and tags(i.e. https://arcadia.yandex.ru/arc/branches/remorph/stable-1/arcadia/), set to null if trunk
    :param timestamp: Timestamp
      Timestamp for caching
    :param only_info: Only Rev
      Skip checkout and only write revision on output
    :param ignore_missing_path: Ignore missing paths in batch mode
      [[Do not fail if some paths in a batch are absent, just skip it from result]]
    :param batch_input:
      Поддержка batch-режима. Пример json-a: https://nirvana.yandex-team.ru/data/0547adaa-bfee-4961-9ba8-09393ca51b7d. Опции кубика игнорируются, за исключением "Depth" и "Ignore Externals"
    """
    raise NotImplementedError("Write your local execution stub here")


class RunPlaygroundSignsMapOutput(NamedTuple):
    export_detections: vh3.JSON
    export_clusters: vh3.JSON
    export_matches: vh3.JSON
    export_clusters_geojson: vh3.JSON


@vh3.decorator.external_operation("https://nirvana.yandex-team.ru/operation/72bd31df-94d6-4ee3-9b58-a2816a820168")
@vh3.decorator.nirvana_names(mrc_config="mrc-config", gt_objects="gt-objects", gt_matches="gt-matches")
@vh3.decorator.nirvana_output_names(
    export_detections="export-detections",
    export_clusters="export-clusters",
    export_matches="export-matches",
    export_clusters_geojson="export-clusters-geojson",
)
@vh3.decorator.nirvana_names_transformer(vh3.name_transformers.snake_to_dash, options=True)
def run_playground_signs_map(
    *,
    yt_token: vh3.Secret = vh3.Factory(lambda: vh3.context.yt_token),
    mr_account: vh3.String = vh3.Factory(lambda: vh3.context.mr_account),
    features: vh3.String,
    secret_version: vh3.String,
    yav_token: vh3.Secret = vh3.Factory(lambda: vh3.context.yav_token),
    mrc_config: vh3.Text,
    migrations: vh3.Binary,
    ya: vh3.Executable,
    playground: vh3.Executable,
    yt_pool: vh3.String = None,
    ttl: vh3.Integer = 360,
    max_ram: vh3.Integer = 1024,
    mr_transaction_policy: vh3.Enum[Literal["MANUAL", "AUTO"]] = "MANUAL",
    gt_objects: vh3.JSON = None,
    gt_matches: vh3.JSON = None
) -> RunPlaygroundSignsMapOutput:
    """
    Run playground [signs_map]

    :param yt_token: YT Token:
      [[ID of Nirvana Secret with YT access token (https://nda.ya.ru/3RSzVU).
    Guide to Nirvana Secrets: https://nda.ya.ru/3RSzWZ]]
      YT OAuth Token.

        [Obtain access token](https://nda.ya.ru/3RSzVU), then [create a Nirvana secret](https://nda.ya.ru/3RSzWZ) and [use it here](https://nda.ya.ru/3RSzWb).
        You can [share the secret](https://nda.ya.ru/3RSzWd) with user(s) and/or a staff group.
    :param mr_account: MR Account:
      [[MR Account Name.
    By default, output tables and directories will be created in some subdirectory of home/<MR Account>/<workflow owner>/nirvana]]
      MR account name (e.g. `rank_machine`) used to build MR output path for this operation.

      See the `mr-output-path` option for more information
    :param yt_pool: YT Pool:
      [[Pool used by YT scheduler. Leave blank to use default pool.
    This option has no effect on YaMR.]]
      Pool used by [YT operation scheduler](https://nda.ya.ru/3Rk4af). Leave this blank to use default pool.
    :param mr_transaction_policy: MR transaction policy:
      Nirvana can automatically prepare, ping and finish MR transaction for this operation: https://nda.ya.ru/3UWdsN
    """
    raise NotImplementedError("Write your local execution stub here")


@vh3.decorator.external_operation("https://nirvana.yandex-team.ru/operation/28afa680-7e65-4bb2-8fed-51c9cf5f513d")
@vh3.decorator.nirvana_names(
    test_objects="test-objects",
    test_clusters="test-clusters",
    gt_objects="gt-objects",
    gt_clusters="gt-clusters",
    valid_classes="valid-classes",
)
@vh3.decorator.nirvana_output_names("quality")
@vh3.decorator.nirvana_names_transformer(vh3.name_transformers.snake_to_dash, options=True)
def clusters_quality_test_signs_map(
    *,
    quality: vh3.Executable,
    test_objects: vh3.JSON,
    test_clusters: vh3.JSON,
    gt_objects: vh3.JSON,
    gt_clusters: vh3.JSON,
    ttl: vh3.Integer = 360,
    max_ram: vh3.Integer = 100,
    valid_classes: vh3.Text = None
) -> vh3.Text:
    """
    Clusters quality test [Signs map]
    """
    raise NotImplementedError("Write your local execution stub here")


@vh3.decorator.external_operation("https://nirvana.yandex-team.ru/operation/e64d446b-fb09-4906-a436-d645e1c6901a")
@vh3.decorator.nirvana_names(
    valid_quality="valid-quality", gt_quality="gt-quality", gt_valid_quality="gt-valid-quality"
)
@vh3.decorator.nirvana_output_names("report")
@vh3.decorator.nirvana_names_transformer(vh3.name_transformers.snake_to_dash, options=True)
def quality_report_signs_map(
    *,
    ttl: vh3.Integer = 360,
    max_ram: vh3.Integer = 100,
    quality: vh3.Text = None,
    valid_quality: vh3.Text = None,
    gt_quality: vh3.Text = None,
    gt_valid_quality: vh3.Text = None
) -> vh3.Text:
    """
    Quality report [Signs map]
    """
    raise NotImplementedError("Write your local execution stub here")


@vh3.decorator.external_operation("https://nirvana.yandex-team.ru/operation/894cb084-f640-445a-a116-83ebc3d50d33")
@vh3.decorator.nirvana_names(file="File")
@vh3.decorator.nirvana_output_names("json")
def convert_any_to_json(
    *,
    file: Union[
        vh3.Binary,
        vh3.Executable,
        vh3.FMLDumpParse,
        vh3.FMLFormula,
        vh3.FMLFormulaSerpPrefs,
        vh3.FMLPool,
        vh3.FMLPrs,
        vh3.FMLSerpComparison,
        vh3.FMLWizards,
        vh3.File,
        vh3.HTML,
        vh3.HiveTable,
        vh3.Image,
        vh3.JSON,
        vh3.MRDirectory,
        vh3.MRFile,
        vh3.MRTable,
        vh3.TSV,
        vh3.Text,
        vh3.XML,
    ],
    sync: Sequence[
        Union[
            vh3.Binary,
            vh3.Executable,
            vh3.FMLDumpParse,
            vh3.FMLFormula,
            vh3.FMLFormulaSerpPrefs,
            vh3.FMLPool,
            vh3.FMLPrs,
            vh3.FMLSerpComparison,
            vh3.FMLWizards,
            vh3.File,
            vh3.HTML,
            vh3.HiveTable,
            vh3.Image,
            vh3.JSON,
            vh3.MRDirectory,
            vh3.MRFile,
            vh3.MRTable,
            vh3.TSV,
            vh3.Text,
            vh3.XML,
        ]
    ] = ()
) -> vh3.JSON:
    """
    Convert any to Json
    """
    raise NotImplementedError("Write your local execution stub here")


@vh3.decorator.external_operation("https://nirvana.yandex-team.ru/operation/c5004c65-d0d4-4497-858d-f956bde74f15")
@vh3.decorator.nirvana_output_names("output")
@vh3.decorator.nirvana_names_transformer(vh3.name_transformers.snake_to_dash, options=True)
def concat_text(*, inputs: Sequence[vh3.Text], ttl: vh3.Integer = 360, max_ram: vh3.Integer = 64) -> vh3.Text:
    """
    Concat text

    Просто склеиваем поступивший на вход текст
    """
    raise NotImplementedError("Write your local execution stub here")
