# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.

"""
All the `deadline farm` commands.
"""

import click
from botocore.exceptions import ClientError  # type: ignore[import]

from ... import api
from ...config import config_file
from ...exceptions import DeadlineOperationError
from .._common import (
    _apply_cli_options_to_config,
    _cli_object_repr,
    _handle_error,
    _suggest_resources_on_client_error,
)
from .._main import deadline as main


@main.group(name="farm")
@_handle_error
def cli_farm():
    """
    Commands to work with [Deadline Cloud farms].

    [Deadline Cloud farms]: https://docs.aws.amazon.com/deadline-cloud/latest/userguide/farms.html
    """


@cli_farm.command(name="list")
@click.option("--profile", help="The AWS profile to use.")
@_handle_error
def farm_list(**args):
    """
    Lists the available [Deadline Cloud farms]. If the AWS profile is created
    from a [Deadline Cloud monitor] login, it will list the farms you have permission to access,
    otherwise it will list all farms.

    [Deadline Cloud farms]: https://docs.aws.amazon.com/deadline-cloud/latest/userguide/farms.html
    [Deadline Cloud monitor]: https://docs.aws.amazon.com/deadline-cloud/latest/userguide/working-with-deadline-monitor.html
    """
    # Get a temporary config object with the standard options handled
    config = _apply_cli_options_to_config(**args)

    try:
        response = api.list_farms(config=config)
    except ClientError as exc:
        suggestion = _suggest_resources_on_client_error(exc, config=config)
        raise DeadlineOperationError(
            f"Failed to get Farms from Deadline:\n{exc}{suggestion}"
        ) from exc

    # Select which fields to print and in which order
    structured_farm_list = [
        {field: farm[field] for field in ["farmId", "displayName"]} for farm in response["farms"]
    ]

    click.echo(_cli_object_repr(structured_farm_list))


@cli_farm.command(name="get")
@click.option("--profile", help="The AWS profile to use.")
@click.option("--farm-id", help="The farm to use.")
@_handle_error
def farm_get(**args):
    """
    Get the details of a [Deadline Cloud farm].

    [Deadline Cloud farm]: https://docs.aws.amazon.com/deadline-cloud/latest/userguide/farms.html
    """
    # Get a temporary config object with the standard options handled
    config = _apply_cli_options_to_config(required_options={"farm_id"}, **args)

    farm_id = config_file.get_setting("defaults.farm_id", config=config)

    deadline = api.get_boto3_client("deadline", config=config)
    try:
        response = deadline.get_farm(farmId=farm_id)
    except ClientError as exc:
        suggestion = _suggest_resources_on_client_error(exc, farm_id=farm_id, config=config)
        raise DeadlineOperationError(
            f"Failed to get Farm from Deadline:\n{exc}{suggestion}"
        ) from exc
    response.pop("ResponseMetadata", None)

    click.echo(_cli_object_repr(response))
