# -*- coding: utf-8 -*- #
# Copyright 2026 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Performs switchover for a Cloud SQL blue-green deployment."""

import argparse
from typing import Any
from apitools.base.py import exceptions as apitools_exceptions
from googlecloudsdk.api_lib.sql import api_util
from googlecloudsdk.api_lib.sql import operations
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope import exceptions as calliope_exceptions
from googlecloudsdk.command_lib.sql import flags as sql_flags
from googlecloudsdk.core import properties
from googlecloudsdk.core.console import console_io


@base.Hidden
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA)
class Switchover(base.Command):
  """Performs switchover for a Cloud SQL blue-green deployment."""

  def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.client = api_util.SqlClient(api_util.API_VERSION_DEFAULT)

  @classmethod
  def Args(cls, parser: argparse.ArgumentParser) -> None:
    """Args is called by calliope to gather arguments for this command.

    Args:
      parser: An argparse parser that you can use to add arguments that go on
        the command line after this command. Positional arguments are allowed.
    """
    del cls  # Unused.
    sql_flags.AddDeploymentId(parser)
    sql_flags.AddRegion(parser, required=False, specify_default_region=False)
    base.ASYNC_FLAG.AddToParser(parser)

  def Run(self, args: argparse.Namespace) -> dict[str, Any]:
    """Performs switchover for a Cloud SQL blue-green deployment.

    Args:
      args: The arguments that this command was invoked with.

    Returns:
      A dictionary object representing the long-running operation resource if
      the switchover was successful.
    Raises:
      HttpException: An HTTP error response was received while executing API
          request.
    """
    sql_client = self.client.sql_client
    sql_messages = self.client.sql_messages
    project = properties.VALUES.core.project.GetOrFail()
    region = args.region
    if not region:
      region = properties.VALUES.compute.region.Get()
    if not region:
      raise calliope_exceptions.RequiredArgumentException(
          '--region',
          'Region not chosen. Specify command-line flag --region or region'
          ' property.'
      )
    deployment_name = f'projects/{project}/locations/{region}/blueGreenDeployments/{args.deployment}'

    console_io.PromptContinue(
        message=(
            f'Blue green deployment {args.deployment} in project {project} and'
            f' region {region} will be switched over.'
        ),
        cancel_on_no=True,
    )

    try:
      request = sql_messages.SqlBlueGreenDeploymentsSwitchoverRequest(
          name=deployment_name,
          switchoverBlueGreenDeploymentRequest=sql_messages.SwitchoverBlueGreenDeploymentRequest(),
      )
      result_operation = sql_client.blueGreenDeployments.Switchover(request)
      operation_ref = self.client.resource_parser.Create(
          'sql.operations', operation=result_operation.name, project=project
      )

      if args.async_:
        return result_operation

      operations.OperationsV1Beta4.WaitForOperation(
          sql_client, operation_ref, 'Switching over blue-green deployment'
      )

      return sql_client.blueGreenDeployments.Get(
          sql_messages.SqlBlueGreenDeploymentsGetRequest(name=deployment_name)
      )
    except apitools_exceptions.HttpError as error:
      raise calliope_exceptions.HttpException(error) from error
