# Copyright (c) 2019 CloudZero - ALL RIGHTS RESERVED - PROPRIETARY AND CONFIDENTIAL
# Unauthorized copying of this file and/or project, via any medium is strictly prohibited.
# Direct all questions to legal@cloudzero.com
#

from pprint import pprint

from src.api.v4_organizations import get_organizations
from src.api.v4_quicksight import update_data_sets
from src.exceptions import APIError
from src.utils.console import eprint


def refresh(org_id):
    """Refresh QuickSight data sets for organizations using V4 API.

    Note: This function has been migrated from V3 dashboard refresh to V4 QuickSight data set refresh.
    """
    org_ids = [org_id]
    all_orgs = org_id == "all"
    response_message = "all organizations" if all_orgs else f"organization {org_id}"

    try:
        if all_orgs:
            org_ids = list(get_organizations().keys())

        # Refresh QuickSight data sets for each organization
        success_count = 0
        failure_count = 0

        for current_org_id in org_ids:
            try:
                # Use V4 QuickSight API to update data sets for this organization
                # This is the closest equivalent to the old dashboard refresh
                response = update_data_sets(
                    data_sets_definition={
                        "organization_id": current_org_id,
                        "dataset_ids": [],  # Empty list refreshes all data sets for org
                    },
                    debug=False,
                )

                if response and response.get("success", False):
                    success_count += 1
                    pprint(f"Successfully refreshed QuickSight data sets for organization {current_org_id}")
                else:
                    failure_count += 1
                    pprint(f"Failed to refresh QuickSight data sets for organization {current_org_id}")

            except APIError as api_error:
                failure_count += 1
                pprint(f"API Error refreshing organization {current_org_id}: {api_error}")
            except Exception as org_error:
                failure_count += 1
                pprint(f"Error refreshing organization {current_org_id}: {org_error}")

        # Summary
        total_orgs = len(org_ids)
        pprint(f"\nDashboard refresh summary for {response_message}:")
        pprint(f"  Total organizations: {total_orgs}")
        pprint(f"  Successful refreshes: {success_count}")
        pprint(f"  Failed refreshes: {failure_count}")

    except Exception as e:
        pprint(f"Failed to refresh dashboards for {response_message}")
        eprint(f"Error: {e}")
