#
# # Copyright © 2026 Peak AI Limited. or its affiliates. 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. A copy of
# # the License is located at:
# #
# # https://github.com/PeakBI/peak-sdk/blob/main/LICENSE
# #
# # or in the "license" file accompanying this file. This file 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.
# #
# # This file is part of the peak-sdk.
# # see (https://github.com/PeakBI/peak-sdk)
# #
# # You should have received a copy of the APACHE LICENSE, VERSION 2.0
# # along with this program. If not, see <https://apache.org/licenses/LICENSE-2.0>
#
"""Resource deletion operations for press deployments."""

from __future__ import annotations

from peak.press import apps, blocks
from peak.press.wrappers.delete.utils import (
    delete_deployment,
    delete_resource_specs,
    get_spec_id,
    validate_deployment_name,
)
from peak.tools.logging import LogLevel, PeakLogger, get_logger

logger: PeakLogger = get_logger(level=LogLevel.INFO)


def delete(
    deployment_name: str,
    *,
    is_app: bool = True,
    suffix: str | None = None,
    delete_specs: bool = False,
) -> tuple[bool, str | None]:
    """Delete an application/block and optionally its associated press resources.

    Args:
        deployment_name: Name of the application/block to delete
        is_app: True if deleting an app, False for a block
        suffix: Optional suffix to filter the spec
        delete_specs: Whether to delete associated press resources

    Returns:
        Tuple of (success status, error message or None)

    Raises:
        ValueError: If deployment_name is invalid
    """
    # Validate input
    if error := validate_deployment_name(deployment_name):
        logger.error("[%s] %s", deployment_name, error)
        return False, error

    try:
        # Initialize clients
        app_client = apps.get_client()
        block_client = blocks.get_client()

        # Get spec ID
        resource_type = "app" if is_app else "block"
        client = app_client if is_app else block_client
        spec_id = get_spec_id(client, deployment_name, suffix)

        if not spec_id:
            error = f"No {resource_type} spec found for {deployment_name}"
            if suffix:
                error += f" with suffix {suffix}"
            logger.warning("[%s] %s", deployment_name, error)
            return False, error

        # Delete deployment
        try:
            delete_deployment(spec_id, client)
        except (RuntimeError, ValueError, KeyError) as e:
            error = f"Failed to delete deployment: {e!s}"
            logger.exception("[%s] %s", deployment_name, error)
            return False, error

        # Delete press resources if requested
        if delete_specs:
            spec_error = delete_resource_specs(spec_id, deployment_name, app_client, block_client, is_app=is_app)
            if spec_error:
                logger.error("[%s] %s", deployment_name, spec_error)
                return False, spec_error

    except (ValueError, RuntimeError, KeyError) as e:
        error = f"Unexpected error during deletion: {e!s}"
        logger.exception("[%s] %s", deployment_name, error)
        return False, error

    logger.info("[%s] Successfully deleted %s", deployment_name, resource_type)
    return True, None
