# Copyright (c) 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
#
#
import csv
import json
import sys
from pathlib import Path

from rich import box
from rich.console import Console
from rich.pretty import pprint
from rich.table import Table

# Removed yachalk import - using rich for text styling instead
from src.api.v4_connections import disable_connection, enable_connection, get_connections_for_org
from src.api.v4_healthcheck import get_connection_healthcheck

# Remove Organizations import since we're using raw dict for v4 API compatibility
# from src.schemas.organizations import Organizations
from src.api.v4_organizations import get_organization_tags, get_organizations, refresh_organization
from src.utils.console import format_account_stage
from src.utils.data import filter_dict
from src.utils.formatting import (
    format_org_data_into_list,
)
from src.utils.organization_status import is_organization_enabled, should_include_in_enabled_filter
from src.utils.time import utc_datetime_from_anything
from src.utils.ui import ProgressFactory, TableFactory


def _get_healthcheck_data_v4(connection_id):
    """Helper function to get healthcheck data using v4 API."""
    try:
        healthcheck_response = get_connection_healthcheck(connection_id, include_details=True, debug=False)
        healthcheck_data = healthcheck_response.model_dump()

        # Extract details and flatten for backward compatibility
        details = healthcheck_data.get("details", {})
        return {
            "is_healthy": healthcheck_data.get("is_healthy", False),
            "30_day_spend": details.get("thirty_day_spend", {}),  # V4 uses 'thirty_day_spend'
            "cur_health": details.get("cur_health", {}),
            "cur_metadata": details.get("cur_metadata", {}),
            **details,  # Include all other details fields
        }
    except Exception:
        return {}


# Removed duplicated __format_org_data_into_list function - now using the centralized version in utils.formatting


def filter_by_query(org_data, query):
    """Filter organizations by ID or name"""
    if not query:
        return org_data

    # Handle case where query is a list (connection list command with multiple org IDs)
    if isinstance(query, list):
        filtered = {}
        for q in query:
            for org_id, org in org_data.items():
                # Match either the org_id (key) or cz_organization_name
                if q.lower() in org_id.lower() or q.lower() in org.get("cz_organization_name", "").lower():
                    filtered[org_id] = org
        return filtered

    # Regular case with a single query string
    filtered = {}
    query_lower = query.lower().strip()  # Strip whitespace from query

    for org_id, org in org_data.items():
        # org_id is the key in the dictionary, cz_organization_name is in the value dict
        org_id_lower = org_id.lower().strip()
        org_name_lower = (org.get("cz_organization_name") or "").lower().strip()

        # Match either the organization ID (key) or cz_organization_name
        if query_lower in org_id_lower or query_lower in org_name_lower:
            filtered[org_id] = org

    return filtered


# Removed duplicated cache functions - now using the centralized versions in utils.cache


def filter_by_age(org_data, max_age_days):
    """Filter organizations by age (in days)"""
    if not max_age_days:
        return org_data

    from datetime import timedelta

    from src.utils.time import utcdatetimenow

    # Calculate the cutoff date using standards.py utility
    cutoff_date = utcdatetimenow() - timedelta(days=int(max_age_days))

    # Filter organizations created after the cutoff date
    filtered = {}
    for org_id, org in org_data.items():
        try:
            created_date = utc_datetime_from_anything(org.get("created", "1970-01-01T00:00:00Z"))
            if created_date and created_date > cutoff_date:
                filtered[org_id] = org
        except ValueError:
            # Skip orgs with unparseable dates for age filtering
            # For debug purposes, we could log these issues here
            pass

    return filtered


def get_organization_data(query, arguments) -> dict[str, dict] | None:
    # By default, only search enabled organizations unless --all flag is specified
    enabled_only = not arguments.get("--all")
    org_type = arguments.get("--type") or ""
    age_filter = arguments.get("--age")

    with ProgressFactory.create_fetch_progress("Loading CloudZero organization data") as progress:
        task1 = progress.add_task("[green]Loading CloudZero organization data", total=4, status="")

        # Handle different query scenarios
        org_data = None

        # Case 1: Specific query provided (ID or name)
        if query:
            progress.update(task1, description="[cyan]Searching for organization", advance=1)

            # Check if query looks like a UUID (ID lookup)
            from src.utils.core import is_valid_uuid

            if is_valid_uuid(query):
                # Try to get specific org by ID
                try:
                    org_response = get_organizations(
                        organization_query=query,
                        debug=arguments and arguments.get("--debug"),
                        enabled_only=enabled_only,
                    )
                    if org_response and query in org_response:
                        org_data = {query: org_response[query].model_dump()}
                except Exception as e:
                    from src.utils.error_handling import handle_organization_loading_error

                    handle_organization_loading_error(e, arguments)
            else:
                # Search by name - use API server-side search
                try:
                    # Pass the query to the API to perform server-side substring search
                    org_response = get_organizations(
                        organization_query=query,
                        debug=arguments and arguments.get("--debug"),
                        enabled_only=enabled_only,
                    )
                    if org_response:
                        # Convert to dict format
                        org_data = {}
                        for org_id, org_details in org_response.items():
                            org_data[org_id] = org_details.model_dump()
                except Exception as e:
                    from src.utils.error_handling import handle_organization_loading_error

                    handle_organization_loading_error(e, arguments)

        # Case 2: No query - get all organizations
        else:
            progress.update(task1, description="[cyan]Loading all organizations", advance=1)
            try:
                org_response = get_organizations(
                    organization_query=None, debug=arguments and arguments.get("--debug"), enabled_only=enabled_only
                )
                if org_response:
                    # Convert to dict format
                    org_data = {}
                    for org_id, org_details in org_response.items():
                        org_data[org_id] = org_details.model_dump()
            except Exception as e:
                from src.utils.error_handling import handle_organization_loading_error

                handle_organization_loading_error(e, arguments)

        if org_data:
            progress.update(task1, description="[cyan]Applying filters", advance=1)

            # Apply type filter
            if org_type:
                org_data = filter_dict(org_data, org_type, field="organization_stage", exact=True, depth=2)

            # Apply enabled filter using consolidated logic
            # Client-side filtering since API enabled_only parameter is not working correctly
            if enabled_only:
                filtered_org_data = {}
                for org_id, org_details in org_data.items():
                    if should_include_in_enabled_filter(org_details, enabled_only):
                        filtered_org_data[org_id] = org_details
                org_data = filtered_org_data

            # Apply age filter
            if age_filter:
                org_data = filter_by_age(org_data, age_filter)

            progress.update(
                task1, advance=2, description=f"[green]{len(org_data) if org_data else 0} organizations loaded"
            )
            # Return raw org_data instead of Organizations model to avoid validation issues with v4 API format
            return org_data
        else:
            progress.update(task1, description="[red]No matching organizations found", advance=3)
            return None


def list_orgs(arguments, organization_data):
    # Use the long form argument name that docopt populates
    output_file = arguments.get("--output")
    sort_by = arguments.get("--sort-by") or "name"  # Default to 'name' if not specified
    show_all = arguments.get("--all", False)  # Check if --all flag is present
    show_autolink = True  # Always show autolink status
    debug_mode = arguments.get("--debug", False)  # Check if --debug flag is present

    # Handle the case where organization_data is None
    if not organization_data:
        from src.utils.error_handling import display_user_friendly_error

        display_user_friendly_error(
            title="No Organizations Found",
            message=(
                "Unable to find any organizations. This could be due to:\n"
                "• Filters that exclude all results (try using --all to see disabled orgs)\n"
                "• API errors (run with --debug to see technical details)\n"
                "• Authentication issues (run 'czops auth test' to verify)"
            ),
            debug=debug_mode,
            exit_code=0,  # Don't exit, just show the message
        )
        return

    console = Console()

    # Handle raw output mode
    if arguments.get("--raw"):
        pprint(organization_data)
        return

    # Use spend data from V4 API (prioritize connections_summary data)
    for org_id, org_details in organization_data.items():
        spend_value = 0.0

        # Prefer connections_summary spend data (as per V4 API spec)
        if connections_summary := org_details.get("connections_summary"):
            if summary_spend := connections_summary.get("total_billed_spend_30_days"):
                try:
                    spend_value = float(summary_spend) if summary_spend else 0.0
                except (ValueError, TypeError):
                    spend_value = 0.0
        else:
            # Use direct field if connections_summary not available
            api_spend = org_details.get("last_30_days_billed_spend", 0.0)
            try:
                spend_value = float(api_spend) if api_spend else 0.0
            except (ValueError, TypeError):
                spend_value = 0.0

        org_details["spend_amount"] = spend_value

    # Use plain_text=True for CSV export to remove formatting
    # When showing all orgs (including disabled), also show disabled date
    org_data = format_org_data_into_list(
        organization_data,
        nice_dates=False,  # Show date-only format (YYYY-MM-DD) not pretty dates
        plain_text=bool(output_file),
        sort_by=sort_by,
        show_disabled_date=show_all,  # Show disabled date column when --all is specified
        show_autolink=show_autolink,  # Show autolink column when --autolink is specified
        debug_mode=debug_mode,
    )

    if output_file:
        try:
            with open(output_file, "w") as csvfile:
                writer = csv.DictWriter(csvfile, fieldnames=org_data[0].keys(), dialect="excel", quoting=csv.QUOTE_ALL)
                writer.writeheader()
                for data in org_data:
                    writer.writerow(data)
            print(f"Exported CZ Organization list as CSV to {output_file}")
        except OSError as error:
            print(f"I/O error ({error})")
            sys.exit(-1)
    else:
        console = Console()

        # Main organizations table
        table = TableFactory.create_organizations_table(
            title="CloudZero Organizations",
            width=None,
        )
        for x in org_data[0]:
            if x == "Organization ID":
                table.add_column(x, no_wrap=True, justify="left", style="bold cyan", min_width=20, max_width=38)
            elif x == "Status":
                table.add_column(x, no_wrap=True, justify="center", min_width=8, max_width=10)
            elif x == "Name":
                table.add_column(x, justify="left", no_wrap=True, overflow="ellipsis", min_width=10, max_width=20)
            elif x == "Stage":
                table.add_column(x, justify="left", no_wrap=True, min_width=8, max_width=12)
            elif x == "Connections":
                table.add_column(x, justify="left", overflow="ellipsis", min_width=8, max_width=18)
            elif x == "#":
                table.add_column(x, justify="right", no_wrap=True, min_width=3, max_width=5)
            elif x == "30-Day Spend":
                table.add_column(x, justify="right", no_wrap=True, style="green", min_width=12)
            elif x == "Created" or x == "Disabled":
                table.add_column(x, justify="left", no_wrap=True, min_width=10, max_width=12)
            elif x == "Autolink":
                table.add_column(x, justify="center", no_wrap=True, min_width=8, max_width=10)
            else:
                table.add_column(x, overflow="ellipsis", justify="left", min_width=8)
        for row in org_data:
            table.add_row(*row.values())
        console.print(table)

        # Summary table
        # Count organizations by stage and status
        stage_counts = {}
        connection_types = set()
        total_connections = 0
        enabled_count = 0
        disabled_count = 0
        total_spend = 0.0

        for org_id, org in organization_data.items():
            # Use v4 API field name (organization_stage)
            stage = org.get("organization_stage")
            if stage is None:
                stage = "Unknown"
            stage_counts[stage] = stage_counts.get(stage, 0) + 1

            # Count enabled vs disabled organizations
            if is_organization_enabled(org):
                enabled_count += 1
            else:
                disabled_count += 1

            # Count total connections (new schema: use connections_summary only)
            connections_summary = org.get("connections_summary", {})
            if total_conn := connections_summary.get("total_connections"):
                try:
                    conn_count = int(total_conn) if isinstance(total_conn, str) else total_conn
                    total_connections += conn_count
                except (ValueError, TypeError):
                    pass

            # Sum up total spend (new schema: use connections_summary only)
            if "spend_amount" in org and isinstance(org["spend_amount"], int | float):
                total_spend += org["spend_amount"]

            # Collect connection types (new schema: use connections_summary only)
            if enabled_providers := connections_summary.get("enabled_providers"):
                for provider in enabled_providers:
                    connection_types.add(provider)

        # Create summary table
        summary = TableFactory.create_summary_table(
            title="Results Summary", key_style="cyan", value_style="green", width=None
        )

        summary.add_row("Total Organizations", str(len(organization_data)))

        # Add enabled/disabled status counts
        if enabled_count > 0:
            summary.add_row("  Enabled", f"{enabled_count} ({enabled_count / len(organization_data) * 100:.0f}%)")
        if disabled_count > 0:
            summary.add_row("  Disabled", f"{disabled_count} ({disabled_count / len(organization_data) * 100:.0f}%)")

        summary.add_row("Total Connections", str(total_connections))
        summary.add_row("Connection Types", ", ".join(sorted(connection_types)))

        # Add total spend
        summary.add_row("Total 30-Day AWS Spend", f"${total_spend:,.2f}")

        # Add stage breakdown
        if stage_counts:
            summary.add_section()
            summary.add_row("Organization Stages", "")
            for stage, count in sorted(stage_counts.items()):
                if stage:  # Skip empty stage
                    summary.add_row(f"  {format_account_stage(stage)}", str(count))

        console.print(summary)


def export_tags_to_file(output_file, data, cz_organization_id):
    # Save to file in JSON format
    try:
        # Convert to Path object for better path handling
        output_path = Path(output_file)

        # Ensure absolute path
        if not output_path.is_absolute():
            output_path = Path.cwd() / output_file

        # Ensure parent directory exists
        output_path.parent.mkdir(parents=True, exist_ok=True)

        # Write data to file
        with open(output_path, "w") as fp:
            json.dump(data, fp, indent=2)

        print(f"Exported {len(data)} tags for organization {cz_organization_id} to {output_path}")
        return True
    except Exception as error:
        print(f"Error writing to file: {error}")
        sys.exit(1)


def list_org_tags(arguments, organization_data):
    # With docopt, short form commands (-o) are converted to long form (--output) in the arguments dict
    output_file = arguments.get("--output")
    debug_mode = arguments.get("--debug", False)

    if debug_mode:
        print(f"DEBUG: Arguments: {arguments}")
        print(f"DEBUG: Output file path: {output_file}")

    # Process only the first organization
    for cz_organization_id, _details in organization_data.items():
        if debug_mode:
            print(f"DEBUG: Fetching tags for organization {cz_organization_id}")

        results = get_organization_tags(cz_organization_id)

        if not results:
            print(f"No tags found for organization {cz_organization_id}")
            return

        # v4 API returns a dict directly, no need to parse JSON
        data = results

        if debug_mode:
            print(f"DEBUG: Found {len(data)} tags for organization {cz_organization_id}")

        # Display message about tag count
        if len(data) > 50:
            print(
                f"Found {len(data)} tags. To export all tags to a file, use: czops org tags {cz_organization_id} -o tags.json"
            )

        # Export to file if requested
        if output_file:
            if debug_mode:
                print(f"DEBUG: Exporting tags to {output_file}")

            if output_file == "-":
                # Print to stdout
                pprint(data)
                return
            else:
                # Export to file and exit
                export_tags_to_file(output_file, data, cz_organization_id)
                return

        # Display in a table
        console = Console(width=None)  # Use full terminal width
        columns = [
            ("Key", {"justify": "left", "style": "cyan", "no_wrap": True, "ratio": 40}),
            ("Value", {"justify": "left", "no_wrap": False, "ratio": 60, "overflow": "crop"}),
        ]
        org_tag_table = TableFactory.create_standard_table(
            title=f"Organization Tags for {cz_organization_id}",
            columns=columns,
            width=None,
        )

        if debug_mode:
            print("DEBUG: Displaying tags in a table")

        # Sort tags alphabetically for better display
        for tag, value in sorted(data.items()):
            org_tag_table.add_row(tag, value)
        console.print(org_tag_table)
        return  # Only process the first organization


# Removed duplicated _get_consolidated_health_status function - now using the centralized version in utils.formatting


def _display_connection_selection_table(connections: list[dict]) -> tuple[Table, list[dict]]:
    """
    Create an abbreviated connection selection table for interactive selection.

    Only AWS connections are selectable (shown with numbers). Other providers are
    displayed but cannot be selected.

    Args:
        connections: List of connection dictionaries (will be sorted by provider, then type)

    Returns:
        Tuple of (Rich Table with abbreviated connection information, list of selectable AWS connections)
    """
    table = Table(box=box.ROUNDED, show_header=True, padding=(0, 1))
    table.add_column("#", style="dim", width=4, justify="right")
    table.add_column("Connection ID", style="cyan", no_wrap=True)
    table.add_column("Connection Name", style="white")
    table.add_column("Provider", style="yellow", max_width=10)
    table.add_column("Type", style="blue", max_width=10)

    # Sort connections by provider, then by type
    sorted_connections = sorted(
        connections, key=lambda c: (c.get("provider", "Unknown"), c.get("connection_type", "UNKNOWN"))
    )

    # Track selectable AWS connections
    selectable_connections = []
    selection_index = 1

    for conn in sorted_connections:
        conn_id = conn.get("connection_id", "Unknown")
        conn_name = conn.get("connection_name", "-")
        provider = conn.get("provider", "Unknown")
        conn_type = conn.get("connection_type", "UNKNOWN")

        # Only AWS connections are selectable
        if provider == "AWS":
            table.add_row(str(selection_index), conn_id, conn_name, provider, conn_type)
            selectable_connections.append(conn)
            selection_index += 1
        else:
            # Non-AWS connections shown without selection number
            table.add_row("[dim]-[/]", conn_id, conn_name, provider, conn_type)

    return table, selectable_connections


def org_healthcheck(arguments, org_data):
    """
    Run healthcheck on connections in an organization with interactive selection.

    Displays organization summary and abbreviated connection list, then allows
    user to select which connections to healthcheck.

    Args:
        arguments (dict): Command line arguments
        org_data (dict): Organization data
    """
    from src.api.v4_healthcheck import get_connection_healthcheck
    from src.features.connections.healthcheck_display import display_healthcheck
    from src.features.info import display_organization_summary

    console = Console()
    debug_mode = arguments.get("--debug", False)

    # Check if we have any organizations
    if not org_data or len(org_data.keys()) == 0:
        console.print("[red]No organizations found with the provided query.[/]")
        console.print("[yellow]Try using 'czops org list' to see available organizations.[/]")
        return

    for org_id, org_details in org_data.items():
        # Display organization summary using reusable function
        display_organization_summary(org_id, org_details)
        console.print()

        # Fetch connections using V4 API (same as czops conn list and org info) for consistent data
        try:
            connections_list = get_connections_for_org(org_id, debug=debug_mode)

            if not connections_list:
                console.print("[yellow]No connections found for this organization.[/]")
                return

            # Convert to list of dicts
            connections = [conn.model_dump() for conn in connections_list]
        except Exception as e:
            console.print(f"[red]ERROR: Failed to fetch connections: {e}[/]")
            if debug_mode:
                import traceback

                console.print(f"[dim]{traceback.format_exc()}[/]")
            return

        # Display abbreviated connection selection table
        selection_table, selectable_connections = _display_connection_selection_table(connections)

        console.print(f"[bold cyan]Available Connections ({len(connections)}):[/]")
        console.print(selection_table)
        console.print()
        console.print("[dim]Note: At this time, only AWS accounts are supported for healthcheck[/]")
        console.print()

        if not selectable_connections:
            console.print("[yellow]No AWS connections available for healthcheck.[/]")
            return

        # Prompt user to select connections for healthcheck
        console.print("[cyan]Select AWS connections to healthcheck:[/]")
        console.print("  Enter connection numbers (comma-separated, e.g., '1,3,5')")
        console.print("  Press Enter to cancel")

        user_input = input("\nSelection: ").strip()

        if not user_input:
            console.print("[yellow]Healthcheck cancelled.[/]")
            return

        # Parse selection
        selected_connections = []
        try:
            indices = [int(idx.strip()) for idx in user_input.split(",")]
            for idx in indices:
                if 1 <= idx <= len(selectable_connections):
                    selected_connections.append(selectable_connections[idx - 1])
                else:
                    console.print(f"[yellow]Warning: Index {idx} is out of range, skipping[/]")
        except ValueError:
            console.print("[red]Invalid input. Please enter numbers separated by commas.[/]")
            return

        if not selected_connections:
            console.print("[yellow]No valid connections selected.[/]")
            return

        console.print(f"\n[green]Running healthcheck on {len(selected_connections)} selected connection(s)...[/]\n")

        # Run healthcheck on selected connections
        for conn in selected_connections:
            conn_id = conn.get("connection_id")
            conn_name = conn.get("connection_name", conn_id)

            console.print(f"[bold cyan]Healthcheck for:[/] {conn_name} ({conn_id})")

            try:
                # Get healthcheck data from API
                healthcheck_response = get_connection_healthcheck(conn_id, include_details=True, debug=debug_mode)

                if healthcheck_response:
                    # Convert to dict and display using the healthcheck display function
                    healthcheck_data = healthcheck_response.model_dump()
                    display_healthcheck(healthcheck_data)
                else:
                    console.print("[yellow]No healthcheck data available for this connection.[/]")

                console.print()
            except Exception as e:
                console.print(f"[red]ERROR: Healthcheck failed for {conn_id}: {e}[/]")
                if debug_mode:
                    import traceback

                    console.print(f"[dim]{traceback.format_exc()}[/]")
                console.print()

        return


def enable_disable(arguments, org_data):
    console = Console()
    query = arguments.get("<ID-or-NAME>")
    if len(org_data.keys()) > 1:
        print(f"Found multiple organizations with a name similar to {query}, please refine your search")
        pprint(org_data)
    elif len(org_data.keys()) == 1:
        for org_id, details in org_data.items():
            org_name = details.get("cz_organization_name", "Unknown")
            if arguments["enable"]:
                print(f"Enabling all accounts for {org_name} ({org_id})")
            elif arguments["disable"]:
                print(f"Disabling all accounts for {org_name} ({org_id})")
            else:
                print(f"You can only enable or disable organizations (you tried {arguments})")
                sys.exit()

            # Fetch connections for this organization using the v4 API
            debug = arguments.get("--debug", False)
            try:
                connections_data = get_connections_for_org(str(org_id), debug=debug)
                if connections_data and len(connections_data) > 0:
                    connection_ids = [
                        conn.get("cloud_account_id") for conn in connections_data if conn.get("cloud_account_id")
                    ]

                    for connection_id in connection_ids:
                        if arguments["enable"]:
                            result = enable_connection(connection_id, debug=debug)
                            action_icon = "[bold bright_green]✓[/]"
                        elif arguments["disable"]:
                            result = disable_connection(connection_id, debug=debug)
                            action_icon = "[bold bright_red]✗[/]"
                        else:
                            print("No idea what you are doing")
                            sys.exit()

                        console.print(f" {action_icon} {connection_id:75}  {result}")
                    print(f"\n{len(connection_ids)} accounts updated")
                else:
                    print(f"No connections found for organization {org_name}")
            except Exception as e:
                if debug:
                    console.print(f"[red]DEBUG: Error fetching connections: {e}[/]")
                    raise
                print(f"Error fetching connections for organization {org_name}: {e}")
    else:
        print(f"No organizations matching {org_data} found, please refine your search")


def refresh_org(arguments: dict, organization_data: dict | None = None) -> None:
    """
    Refresh a single organization's data in ops-services-data.

    Triggers a fast refresh to sync ops-services-data with reactor-accounts database.
    Runs asynchronously by default.

    Args:
        arguments: Command arguments from docopt
        organization_data: Pre-fetched organization data (optional)
    """
    console = Console()
    debug = arguments.get("--debug", False)
    org_id = arguments.get("<ORG-ID>")

    if not org_id:
        console.print("[red]Error: Organization ID is required[/]")
        sys.exit(1)

    # Get org data if not provided
    if not organization_data:
        try:
            orgs = get_organizations(debug=debug)
            if org_id not in orgs:
                console.print(f"[red]Error: Organization {org_id} not found[/]")
                sys.exit(1)
            organization_data = orgs[org_id].model_dump()
        except Exception as e:
            console.print(f"[red]Error fetching organization: {e}[/]")
            sys.exit(1)

    org_name = organization_data.get("cz_organization_name", "Unknown")

    console.print(f"\n[bold cyan]Refreshing organization data for {org_name}[/bold cyan]")
    console.print(f"[dim]Organization ID: {org_id}[/dim]\n")

    try:
        # Always use async mode for better UX
        result = refresh_organization(org_id, async_mode=True, debug=debug)

        if result.get("status") == "processing":
            console.print("[bold green]✅ SUCCESS[/bold green] - Organization refresh started\n")
            console.print("[dim]The refresh is running in the background.[/dim]")
            console.print("[dim]Data will be updated within a few seconds.[/dim]")
        elif result.get("status") == "success":
            orgs_written = result.get("organizations_written", 0)
            conns_written = result.get("connections_written", 0)
            duration = result.get("duration_ms", 0)

            console.print("[bold green]✅ SUCCESS[/bold green] - Organization data refreshed\n")

            stats_table = Table(title="Refresh Statistics", box=box.ROUNDED)
            stats_table.add_column("Metric", style="dim")
            stats_table.add_column("Value", style="cyan")

            stats_table.add_row("Organizations Updated", str(orgs_written))
            stats_table.add_row("Connections Updated", str(conns_written))
            stats_table.add_row("Duration", f"{duration}ms")

            console.print(stats_table)
        else:
            console.print(f"[yellow]Refresh status: {result.get('status', 'unknown')}[/yellow]")

    except Exception as e:
        console.print("\n[bold red]❌ FAILED[/bold red] - Failed to refresh organization\n")
        console.print(f"[red]Error: {e}[/]")
        if debug:
            raise
        sys.exit(1)
