# 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
#
#
from __future__ import annotations

import csv
import json
import sys
from pathlib import Path
from typing import TYPE_CHECKING

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

if TYPE_CHECKING:
    from src.api.v4_organizations import OrganizationDetails

# Removed yachalk import - using rich for text styling instead
from src.api.v4_connections import disable_connection, enable_connection
from src.api.v4_healthcheck import get_connection_healthcheck
from src.api.v4_organizations import get_organization_tags, get_organizations, refresh_organization
from src.utils.console import format_account_stage
from src.utils.formatting import (
    format_org_data_into_list,
)
from src.utils.organization_status import is_organization_enabled
from src.utils.time import utc_datetime_from_anything
from src.utils.ui import ProgressFactory, TableFactory

# Removed duplicated __format_org_data_into_list function - now using the centralized version in utils.formatting
# Removed filter_by_query - API handles server-side search via organization_query parameter


def _filter_by_type_pydantic(
    org_data: dict[str, OrganizationDetails],
    org_type: str,
) -> dict[str, OrganizationDetails]:
    """Filter organizations by type using Pydantic models."""
    filtered = {}
    org_type_lower = org_type.lower()
    for org_id, org in org_data.items():
        stage = org.organization_stage or ""
        if org_type_lower in stage.lower():
            filtered[org_id] = org
    return filtered


def _filter_by_age_pydantic(
    org_data: dict[str, OrganizationDetails],
    max_age_days: str | int,
) -> dict[str, OrganizationDetails]:
    """Filter organizations by age using Pydantic models."""
    from datetime import timedelta

    from src.utils.time import utcdatetimenow

    cutoff_date = utcdatetimenow() - timedelta(days=int(max_age_days))
    filtered = {}
    for org_id, org in org_data.items():
        try:
            created_date = utc_datetime_from_anything(org.created or "1970-01-01T00:00:00Z")
            if created_date and created_date > cutoff_date:
                filtered[org_id] = org
        except (ValueError, TypeError):
            pass
    return filtered


def get_organization_data(query, arguments) -> dict[str, OrganizationDetails] | dict | None:
    """Fetch organization data with single API call, returning Pydantic models or raw dict."""

    enabled_only = not arguments.get("--all")
    org_type = arguments.get("--type") or ""
    age_filter = arguments.get("--age")
    debug = arguments.get("--debug", False)
    raw = arguments.get("--raw", False)

    with ProgressFactory.create_fetch_progress("Loading CloudZero organization data") as progress:
        task1 = progress.add_task("[green]Loading CloudZero organization data", total=4, status="")
        progress.update(task1, description="[cyan]Fetching organizations", advance=1)

        try:
            # Single API call - API handles UUID vs name search server-side
            org_response = get_organizations(
                organization_query=query,
                debug=debug,
                enabled_only=enabled_only,  # API handles filtering server-side
                raw=raw,
            )
        except Exception as e:
            from src.utils.error_handling import handle_organization_loading_error

            handle_organization_loading_error(e, arguments)
            return None

        if not org_response:
            if debug:
                from src.utils.console import eprint

                eprint(f"DEBUG: API returned empty response for query='{query}', enabled_only={enabled_only}")
            progress.update(task1, description="[red]No matching organizations found", advance=3)
            return None

        # If raw mode, return immediately without filters (full API response)
        if raw:
            org_count = org_response.get("total_count", len(org_response.get("organizations", {})))
            progress.update(task1, advance=3, description=f"[green]{org_count} organizations loaded (raw)")
            return org_response

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

        # Only apply client-side filters that API doesn't support
        filtered_orgs = org_response

        if org_type:
            filtered_orgs = _filter_by_type_pydantic(filtered_orgs, org_type)

        if age_filter:
            filtered_orgs = _filter_by_age_pydantic(filtered_orgs, age_filter)

        progress.update(task1, advance=2, description=f"[green]{len(filtered_orgs)} organizations loaded")
        return filtered_orgs if filtered_orgs else 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

    # Parse limit argument
    limit = arguments.get("--limit")
    if limit:
        limit = int(limit)

    # 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 JSON output (actual JSON, machine-readable)
    if arguments.get("--raw"):
        raw_data = {}
        for org_id, org in organization_data.items():
            if hasattr(org, "model_dump"):
                raw_data[org_id] = org.model_dump()
            else:
                raw_data[org_id] = org
        print(json.dumps(raw_data, indent=2, default=str))
        return

    # Handle formatted dict output (human-readable via pprint)
    if arguments.get("--json"):
        raw_data = {}
        for org_id, org in organization_data.items():
            if hasattr(org, "model_dump"):
                raw_data[org_id] = org.model_dump()
            else:
                raw_data[org_id] = org
        pprint(raw_data)
        return

    # Apply limit after all filters
    if limit:
        from src.utils.data import apply_limit

        organization_data = apply_limit(organization_data, limit)

    # 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
    )

    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 == "Domain":
                table.add_column(x, justify="left", no_wrap=True, overflow="ellipsis", min_width=15, max_width=25)
            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():
            # Convert Pydantic model to dict for processing
            org_dict = org.model_dump() if hasattr(org, "model_dump") else org

            # Use v4 API field name (organization_stage)
            stage = org_dict.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_dict):
                enabled_count += 1
            else:
                disabled_count += 1

            # Count total connections and sum spend from connections_summary
            connections_summary = org_dict.get("connections_summary", {})
            if isinstance(connections_summary, dict):
                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 spend from connections_summary
                if summary_spend := connections_summary.get("total_billed_spend_30_days"):
                    try:
                        total_spend += float(summary_spend) if summary_spend else 0.0
                    except (ValueError, TypeError):
                        pass

                # Collect connection types
                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)

    # Parse limit argument
    limit = arguments.get("--limit")
    if limit:
        limit = int(limit)

    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

        # Apply limit after all filters
        if limit:
            from src.utils.data import apply_limit

            data = apply_limit(data, limit)

        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("Types", style="blue", max_width=20)

    # Sort connections by provider, then by types
    sorted_connections = sorted(
        connections,
        key=lambda c: (c.get("provider", "Unknown"), ",".join(c.get("connection_types", []))),
    )

    # 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_types = conn.get("connection_types", [])
        types_display = ", ".join(conn_types) if conn_types else "UNKNOWN"

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

    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.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():
        # Convert Pydantic model to dict if needed
        org_dict = org_details.model_dump() if hasattr(org_details, "model_dump") else org_details

        # Display organization summary using reusable function
        display_organization_summary(org_id, org_dict)
        console.print()

        # Fetch per-connection data via dedicated API
        from src.api.v4_connections import get_connections_for_org

        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

        # Deduplicate by connection_id
        seen_connection_ids = set()
        connections = []
        for conn in connections_list:
            conn_dict = conn.model_dump() if hasattr(conn, "model_dump") else conn
            conn_id = conn_dict.get("connection_id")
            if conn_id and conn_id not in seen_connection_ids:
                seen_connection_ids.add(conn_id)
                connections.append(conn_dict)

        # 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>")
    debug = arguments.get("--debug", False)

    if len(org_data.keys()) > 1:
        print(f"Found multiple organizations with a name similar to {query}, please refine your search")
        # Convert Pydantic models to dicts for pprint
        raw_data = {}
        for org_id, org in org_data.items():
            if hasattr(org, "model_dump"):
                raw_data[org_id] = org.model_dump()
            else:
                raw_data[org_id] = org
        pprint(raw_data)
    elif len(org_data.keys()) == 1:
        for org_id, details in org_data.items():
            # Convert Pydantic model to dict if needed
            details_dict = details.model_dump() if hasattr(details, "model_dump") else details
            org_name = details_dict.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 per-connection data via dedicated API
            from src.api.v4_connections import get_connections_for_org

            connections_list = get_connections_for_org(org_id, debug=debug)
            if connections_list:
                # Extract unique connection IDs
                seen_ids = set()
                connection_ids = []
                for conn in connections_list:
                    conn_dict = conn.model_dump() if hasattr(conn, "model_dump") else conn
                    conn_id = conn_dict.get("connection_id")
                    if conn_id and conn_id not in seen_ids:
                        seen_ids.add(conn_id)
                        connection_ids.append(conn_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}")
    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 (resolved from ID or name)
    """
    console = Console()
    debug = arguments.get("--debug", False)
    query = arguments.get("<ID-or-NAME>")

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

    # Handle organization resolution
    if not organization_data:
        console.print(f"[red]Error: No organizations found matching '{query}'[/]")
        sys.exit(1)

    if len(organization_data) > 1:
        console.print(f"[yellow]Found multiple organizations matching '{query}'. Please refine your search:[/]\n")
        for org_id, details in organization_data.items():
            # Handle Pydantic models
            if hasattr(details, "cz_organization_name"):
                org_name = details.cz_organization_name or "Unknown"
            elif isinstance(details, dict):
                org_name = details.get("cz_organization_name", "Unknown")
            else:
                org_name = "Unknown"
            console.print(f"  • {org_name} ({org_id})")
        sys.exit(1)

    if len(organization_data) == 0:
        console.print(f"[red]Error: No organizations found matching '{query}'[/]")
        sys.exit(1)

    # Extract the single organization
    org_id = list(organization_data.keys())[0]
    org_details = organization_data[org_id]
    # Handle Pydantic models
    if hasattr(org_details, "cz_organization_name"):
        org_name = org_details.cz_organization_name or "Unknown"
    elif isinstance(org_details, dict):
        org_name = org_details.get("cz_organization_name", "Unknown")
    else:
        org_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)
