# Copyright (c) 2025 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 rich import box
from rich.console import Console
from rich.panel import Panel
from rich.table import Table

from src.api.v4_connections import get_connection, get_connections, get_connections_for_org
from src.constants import NO_ACCOUNT_NAME, NO_ORG_NAME
from src.features.organizations import get_organization_data
from src.utils.console import eprint, format_account_stage
from src.utils.data import looks_like_a_connection_id

console = Console(width=160, highlight=False)


# Removed duplicated __format_account_stage function - now using the centralized version in utils.interface


def display_organization_summary(org_id: str, org_details: dict) -> None:
    """
    Display organization summary information (reusable across commands).

    This function displays the organization header and details table showing
    org metadata, connection counts, providers, spending, and capabilities.

    Args:
        org_id: Organization ID
        org_details: Dictionary containing organization details from V4 API
    """
    org_name = org_details.get("cz_organization_name", NO_ORG_NAME)

    # Create header
    header = Panel(
        f"[bold cyan]{org_name}[/] ([cyan]{org_id}[/])",
        title="Organization Info",
        title_align="left",
        border_style="cyan",
    )
    console.print(header)

    # Create details table
    details_table = Table(box=box.ROUNDED, show_header=False, padding=(0, 2), width=None)
    details_table.add_column("Property", style="bold blue", justify="right")
    details_table.add_column("Value", style="white")

    # Add organization details using exact V4 API field names
    details_table.add_row("ID", org_details.get("cz_organization_id"))
    details_table.add_row("Name", org_details.get("cz_organization_name"))
    details_table.add_row(
        "Status", "[green]Enabled[/]" if org_details.get("organization_enabled") else "[red]Disabled[/]"
    )
    details_table.add_row("Stage", format_account_stage(org_details.get("organization_stage")))
    details_table.add_row("Website", org_details.get("website") or "N/A")
    details_table.add_row("Created", org_details.get("created_at") or "Unknown")

    # Use connections_summary data (new simplified schema)
    connections_summary = org_details.get("connections_summary", {})

    # Connection counts
    if total_connections := connections_summary.get("total_connections"):
        details_table.add_row("Total Connections", str(total_connections))

    if enabled_connections := connections_summary.get("total_enabled_connections"):
        if str(enabled_connections) != str(total_connections):
            details_table.add_row("Enabled Connections", str(enabled_connections))

    # Provider information
    if enabled_providers := connections_summary.get("enabled_providers"):
        details_table.add_row("Active Providers", ", ".join(enabled_providers))

    if all_providers := connections_summary.get("all_providers"):
        if all_providers != enabled_providers:
            details_table.add_row("All Providers", ", ".join(all_providers))

    # Spending information
    if total_spend := connections_summary.get("total_billed_spend_30_days"):
        try:
            spend_value = float(total_spend) if total_spend else 0.0
            if spend_value > 0:
                details_table.add_row("30-Day AWS Spend", f"${spend_value:,.2f}")
        except (ValueError, TypeError):
            pass

    # Connection intelligence
    if connections := connections_summary.get("connections"):
        # Count healthy vs total connections
        healthy_connections = sum(1 for conn in connections.values() if conn.get("is_healthy"))
        details_table.add_row("Healthy Connections", f"{healthy_connections} of {len(connections)}")

        # Show billing-enabled connections
        billing_connections = sum(1 for conn in connections.values() if conn.get("connection_types", {}).get("billing"))
        if billing_connections > 0:
            details_table.add_row("Billing Connections", str(billing_connections))

        # Show metrics-enabled connections
        metrics_connections = sum(1 for conn in connections.values() if conn.get("connection_types", {}).get("metrics"))
        if metrics_connections > 0:
            details_table.add_row("Metrics Connections", str(metrics_connections))

        # Auto-link status (derived from connections)
        auto_link_enabled = any(conn.get("auto_link", {}).get("enabled", False) for conn in connections.values())
        details_table.add_row("Autolink", "[green]Yes[/]" if auto_link_enabled else "[red]No[/]")

    # Show auto link configuration details from connections (new schema pattern)
    if connections := connections_summary.get("connections"):
        # Find connections with auto-link enabled and show role info
        auto_link_connections = [conn for conn in connections.values() if conn.get("auto_link", {}).get("enabled")]
        if auto_link_connections:
            # Show role name from first auto-link enabled connection
            if role_name := auto_link_connections[0].get("auto_link", {}).get("role_name"):
                details_table.add_row("Auto-Link Role", role_name)
            details_table.add_row("Auto-Link Payers", str(len(auto_link_connections)))

    # Show CUR configuration from connections (new schema: per-connection CUR config)
    if connections := connections_summary.get("connections"):
        # Find first connection with CUR configuration
        cur_connections = [
            conn
            for conn in connections.values()
            if conn.get("cz_cur_config") and conn.get("cz_cur_config").get("bucket_name")
        ]
        if cur_connections:
            cur_config = cur_connections[0]["cz_cur_config"]
            if bucket_name := cur_config.get("bucket_name"):
                details_table.add_row("CUR Bucket", bucket_name)
            if report_name := cur_config.get("report_name"):
                details_table.add_row("CUR Report", report_name)
            if is_healthy := cur_config.get("is_healthy"):
                details_table.add_row("CUR Health", "[green]Healthy[/]" if is_healthy else "[red]Unhealthy[/]")

    # Show organizational capabilities derived from connections (new schema pattern)
    if connections := connections_summary.get("connections"):
        # Billing enabled: any connection has billing
        billing_enabled = any(conn.get("connection_types", {}).get("billing", False) for conn in connections.values())
        details_table.add_row("Billing Enabled", "[green]Yes[/]" if billing_enabled else "[red]No[/]")

        # Resources enabled: any connection has resources
        resources_enabled = any(
            conn.get("connection_types", {}).get("resources", False) for conn in connections.values()
        )
        details_table.add_row("Resources Enabled", "[green]Yes[/]" if resources_enabled else "[red]No[/]")

        # Metrics enabled: any connection has metrics
        metrics_enabled = any(conn.get("connection_types", {}).get("metrics", False) for conn in connections.values())
        details_table.add_row("Metrics Enabled", "[green]Yes[/]" if metrics_enabled else "[red]No[/]")

        # Cloud provider breakdown derived from connections
        provider_counts = {}
        for conn in connections.values():
            provider = conn.get("provider", "Unknown")
            provider_counts[provider] = provider_counts.get(provider, 0) + 1

        for provider, count in sorted(provider_counts.items()):
            if provider != "Unknown" and count > 0:
                details_table.add_row(f"{provider} Connections", str(count))

    # Show metadata
    if last_updated := org_details.get("last_updated"):
        details_table.add_row("Last Updated", last_updated)

    if first_seen := org_details.get("first_seen"):
        details_table.add_row("First Seen", first_seen)

    if record_sources := org_details.get("record_sources"):
        if record_sources and isinstance(record_sources, list):
            details_table.add_row("Data Sources", ", ".join(record_sources))

    console.print(details_table)


def display_organization_info(arguments, organization_data):
    """Display detailed information about a single organization."""
    if len(organization_data.keys()) > 1:
        print("Found multiple organizations matching your query. Please refine your search.")
        for org_id, org_details in organization_data.items():
            org_name = org_details.get("cz_organization_name", NO_ORG_NAME)
            print(f"  - {org_name} ({org_id})")
        return

    # Check if JSON output is requested
    if arguments.get("--json"):
        import json

        print(json.dumps(organization_data, indent=2))
        return

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

        # Fetch connections using V4 API (same as czops conn list) for consistent display
        try:
            from src.features.connections.list import (
                _get_connection_composite_key,
                display_connections_for_organization,
            )

            connections_list = get_connections_for_org(org_id, debug=False)

            if connections_list:
                # Convert to the format expected by display function
                connection_data = {}
                for conn in connections_list:
                    conn_dict = conn.model_dump()
                    composite_key = _get_connection_composite_key(conn_dict)
                    connection_data[composite_key] = conn_dict

                # Display connections using the standardized function
                display_connections_for_organization(org_id, organization_data, connection_data, show_header=False)
        except Exception:  # noqa: S112
            # If we can't fetch connections, skip the connection list display
            pass

        # Add link to web UI
        console.print(
            f"\n[cyan]Web Console:[/] [link=https://app.cloudzero.com?organization_id={org_id}]https://app.cloudzero.com?organization_id={org_id}[/link]\n"
        )


def display_connection_info(arguments, connection_id, organization_data=None):
    """Display detailed information about a single connection."""
    # Variables to track connection discovery
    connection_data = None
    found = False
    org_id = None
    org_name = NO_ORG_NAME

    # Debug output
    debug_mode = arguments.get("--debug", False)
    if debug_mode:
        eprint(f"DEBUG: Looking up connection info for ID or name '{connection_id}'")

    # Direct lookup of connection using get_connection API
    with console.status("[cyan]Finding connection info..."):
        # First try direct connection lookup by ID - this is the efficient way
        if debug_mode:
            eprint("DEBUG: Fetching connection data directly with get_connection")
        try:
            connection_v4 = get_connection(connection_id, debug=debug_mode)
            if connection_v4:
                # Successfully retrieved connection directly
                found = True
                org_id = connection_v4.cz_organization_id
                # Store the actual connection data for later use
                connection_data = {"direct_connection": connection_v4.model_dump()}

                if debug_mode:
                    eprint(f"DEBUG: Successfully retrieved connection {connection_id}")
                    eprint("DEBUG: Connection found directly using get_connection API")
                    eprint(f"DEBUG: Organization ID: {org_id}")

                # If we have organization data, try to get the org name
                if organization_data and org_id and org_id in organization_data:
                    org_name = organization_data.get(org_id, {}).get("cz_organization_name", NO_ORG_NAME)
            else:
                connection_data = None
                if debug_mode:
                    eprint("DEBUG: get_connection returned None - connection not found or no access")
        except Exception as e:
            connection_data = None
            if debug_mode:
                eprint(f"DEBUG: Exception in get_connection: {e}")

        # Fallback: Try name-based search using get_connections if direct lookup failed
        if not found:
            if debug_mode:
                eprint(
                    f"DEBUG: Direct lookup failed, trying name-based search with get_connections(name='{connection_id}')"
                )

            try:
                matching_connections = get_connections(name=connection_id, enabled_only=False, debug=debug_mode)

                if debug_mode:
                    eprint(f"DEBUG: Name search returned {len(matching_connections)} results")

                if len(matching_connections) == 1:
                    # Exactly one match - display it
                    connection_v4 = matching_connections[0]
                    found = True
                    org_id = connection_v4.cz_organization_id
                    connection_data = {"direct_connection": connection_v4.model_dump()}

                    if debug_mode:
                        eprint(f"DEBUG: Found single matching connection: {connection_v4.connection_id}")

                    # If we have organization data, try to get the org name
                    if organization_data and org_id and org_id in organization_data:
                        org_name = organization_data.get(org_id, {}).get("cz_organization_name", NO_ORG_NAME)

                elif len(matching_connections) > 1:
                    # Multiple matches - show list and ask user to be more specific
                    console.print(f"\n[yellow]Multiple connections found matching '[cyan]{connection_id}[/cyan]'[/]\n")
                    console.print(
                        f"Found [bold]{len(matching_connections)}[/] connections. Please specify the exact connection ID:\n"
                    )

                    # Create a table to display matches
                    table = Table(show_header=True, header_style="bold cyan", box=None, padding=(0, 2))
                    table.add_column("Connection ID", style="yellow")
                    table.add_column("Name", style="bright_white")
                    table.add_column("Provider", style="cyan")
                    table.add_column("Organization ID", style="dim")

                    for conn in matching_connections:
                        conn_dict = conn.model_dump()
                        table.add_row(
                            conn_dict.get("connection_id", "Unknown"),
                            conn_dict.get("connection_name") or NO_ACCOUNT_NAME,
                            conn_dict.get("provider", "Unknown"),
                            conn_dict.get("cz_organization_id", "Unknown"),
                        )

                    console.print(table)
                    console.print("\n[cyan]💡 To view a specific connection:[/]")
                    console.print("  [white]czops connection info <CONNECTION_ID>[/]\n")
                    return
                else:
                    # No matches at all
                    if debug_mode:
                        eprint("DEBUG: Name search returned no results")

            except Exception as search_error:
                if debug_mode:
                    eprint(f"DEBUG: Exception during name-based search: {search_error}")

        # Fallback: try to find the organization that owns this connection if direct lookup failed
        if not found and (all_orgs := organization_data):
            if debug_mode:
                eprint("DEBUG: Direct lookup failed, falling back to search through organizations")

            for o_id, org_details in all_orgs.items():
                # Check if this connection belongs to this organization
                if connection_id in org_details.get("connections", []):
                    org_id = o_id
                    org_name = org_details.get("cz_organization_name", NO_ORG_NAME)

                    if debug_mode:
                        eprint(f"DEBUG: Found connection in organization {org_id}")

                    # Get detailed connection data using the found organization
                    try:
                        connections_list = get_connections_for_org(org_id, debug=debug_mode)
                        # Convert to legacy format
                        connection_data = {"data": {org_id: {conn["connection_id"]: conn for conn in connections_list}}}
                        if connection_id in connection_data.get("data", {}).get(org_id, {}):
                            found = True
                            break
                    except Exception as e:
                        # Continue searching if this organization fails
                        if debug_mode:
                            eprint(f"[yellow]DEBUG: Failed to get org {org_id}: {e}[/]")
                        continue

        # Last resort: try to fetch all orgs if we don't have them and haven't found the connection yet
        if not found and not organization_data:
            if debug_mode:
                eprint("DEBUG: No organization data provided, fetching all organizations")

            # Only fetch if we don't already have the data
            org_args = {"--all": True}
            all_orgs = get_organization_data(None, org_args)

            if all_orgs:
                for o_id, org_details in all_orgs.items():
                    # Check if this connection belongs to this organization
                    if connection_id in org_details.get("connections", []):
                        org_id = o_id
                        org_name = org_details.get("cz_organization_name", NO_ORG_NAME)

                        if debug_mode:
                            eprint(f"DEBUG: Found connection in organization {org_id}")

                        # Get detailed connection data
                        try:
                            connections_list = get_connections_for_org(org_id, debug=debug_mode)
                            # Convert to legacy format
                            connection_data = {
                                "data": {org_id: {conn["connection_id"]: conn for conn in connections_list}}
                            }
                            if connection_id in connection_data.get("data", {}).get(org_id, {}):
                                found = True
                                break
                        except Exception as e:
                            # Continue searching if this organization fails
                            if debug_mode:
                                eprint(f"[yellow]DEBUG: Failed to get org {org_id}: {e}[/]")
                            continue

    if not found or not connection_data:
        console.print(f"[red]Error:[/] Connection '{connection_id}' not found or you don't have access to it.")
        return

    # Get the connection details - handle both direct connection format and legacy format
    connection = None

    # First, check if we have a direct connection (from get_connection API)
    if "direct_connection" in connection_data:
        connection = connection_data["direct_connection"]
        if debug_mode:
            eprint("DEBUG: Using direct connection data")
    # Fallback: check legacy format
    elif org_id and "data" in connection_data:
        connection = connection_data.get("data", {}).get(org_id, {}).get(connection_id)
        if debug_mode:
            eprint("DEBUG: Using legacy format connection data from org-specific lookup")
    # Last fallback: try to find in any organization (there should only be one)
    elif "data" in connection_data:
        for org_data in connection_data.get("data", {}).values():
            if connection_id in org_data:
                connection = org_data[connection_id]
                if debug_mode:
                    eprint("DEBUG: Found connection in legacy format from fallback search")
                break

    if not connection:
        console.print("[red]Error:[/] Connection info not available.")
        if debug_mode:
            eprint(f"DEBUG: Connection data structure: {connection_data}")
            eprint(f"DEBUG: Could not find connection {connection_id} in any format")
        return

    # Get org info - fetch organization data if not provided
    if organization_data is None and org_id:
        # Fetch organization data using the org_id from connection
        try:
            organization_data = get_organization_data(org_id, {"info": True})
        except Exception:
            organization_data = None

    org_name = (
        NO_ORG_NAME
        if organization_data is None
        else organization_data.get(org_id, {}).get("cz_organization_name", NO_ORG_NAME)
    )

    # Check if JSON output is requested
    if arguments.get("--json"):
        import json

        connection_with_org = {"organization_id": org_id, "cz_organization_name": org_name, "connection": connection}
        print(json.dumps(connection_with_org, indent=2))
        return

    # Create header using V4 API fields
    conn_name = connection.get("connection_name", NO_ACCOUNT_NAME)
    header = Panel(
        f"[bold cyan]{conn_name}[/] ([cyan]{connection_id}[/]) in [bold blue]{org_name}[/]",
        title="Connection Info",
        title_align="left",
        border_style="cyan",
    )
    console.print(header)

    # Create details table with width-aware formatting - get actual terminal width
    import os
    import shutil

    # Try multiple methods to get terminal width dynamically
    term_width = None
    try:
        # Method 1: Use shutil.get_terminal_size (most reliable)
        term_width = shutil.get_terminal_size().columns
    except Exception:
        pass

    if not term_width:
        try:
            # Method 2: Environment variables (useful for testing with COLUMNS=80)
            term_width = int(os.environ.get("COLUMNS", 0))
        except (ValueError, TypeError):
            pass

    if not term_width:
        try:
            # Method 3: Use Rich console's width detection as fallback
            if hasattr(console, "size"):
                term_width = console.size.width
            elif hasattr(console, "width"):
                term_width = console.width
        except Exception:
            pass

    # Fallback to reasonable default
    if not term_width or term_width < 50:
        term_width = 120

    # Adaptive column sizing based on terminal width
    if term_width <= 80:
        # Narrow terminal - use shorter property labels
        property_col_width = 18
        value_col_max = max(35, term_width - 28)  # Leave more space for narrow terminals
        table_width = term_width - 4  # Account for terminal margins
    elif term_width <= 120:
        # Medium terminal
        property_col_width = 20
        value_col_max = max(50, term_width - 32)
        table_width = min(term_width - 2, 120)
    else:
        # Wide terminal
        property_col_width = 22
        value_col_max = max(60, term_width - 36)
        table_width = min(term_width, 150)

    details_table = Table(
        box=box.ROUNDED,
        show_header=False,
        padding=(0, 1 if term_width <= 80 else 2),
        width=table_width,
        expand=False,  # Don't expand to full width
    )
    details_table.add_column("Property", style="bold blue", justify="right", no_wrap=True, width=property_col_width)
    details_table.add_column("Value", style="white", overflow="fold", no_wrap=False, max_width=value_col_max)

    # Add connection details
    details_table.add_row("Connection ID", connection_id)
    details_table.add_row("Name", conn_name)
    details_table.add_row("Organization", f"{org_name} ({org_id})")
    details_table.add_row(
        "Status", "[green]Connected[/]" if connection.get("is_connected", False) else "[red]Disconnected[/]"
    )
    details_table.add_row("Provider", connection.get("provider", "Unknown"))

    # Account type from V4 API fields (clean interface, no backward compatibility)
    account_types = []
    if connection.get("is_cost_connection", False):
        account_types.append("Payer")
    if connection.get("is_resource_connection", False):
        account_types.append("Resource")

    details_table.add_row("Account Type", ", ".join(account_types) if account_types else "Unknown")

    # Timestamps
    def format_value(val):
        """Format a value, handling None, empty, lists, and other data types gracefully."""
        if val is None:
            return "[dim]None[/]"
        if val == "":
            return "[dim]Empty[/]"

        # Handle list type specially with better formatting
        if isinstance(val, list):
            if not val:  # Empty list
                return "[dim]Empty list[/]"
            # Format as comma-separated values or multi-line for longer lists
            if len(val) <= 5 or all(len(str(item)) < 15 for item in val):
                return ", ".join(str(item) for item in val)
            else:
                return "\n" + "\n".join(f"- {item}" for item in val)

        # Handle dictionaries with nice formatting
        if isinstance(val, dict):
            if not val:  # Empty dict
                return "[dim]Empty dict[/]"
            # Format as a readable multi-line representation
            return "\n" + "\n".join(f"- {k}: {v}" for k, v in val.items())

        # Handle boolean values with colored formatting
        if isinstance(val, bool):
            return f"[green]{val}[/]" if val else f"[red]{val}[/]"

        # Default string representation
        return str(val)

    # Timestamps - V4 API fields only
    details_table.add_row("Created", format_value(connection.get("created_at")))
    details_table.add_row("Last Updated", format_value(connection.get("last_updated")))

    # Fix timestamp display - show actual values from API response
    first_seen = connection.get("first_seen")
    last_seen = connection.get("last_seen")
    details_table.add_row("First Seen", format_value(first_seen))
    details_table.add_row("Last Seen", format_value(last_seen))
    details_table.add_row("Last Health Check", format_value(connection.get("last_health_check")))

    # Health status with proper formatting
    health_status = connection.get("is_healthy", False)
    details_table.add_row("Health Status", "[green]Healthy[/]" if health_status else "[red]Unhealthy[/]")
    if health_detail := connection.get("health_status"):
        details_table.add_row("Health Details", format_value(health_detail))

    # Regions - V4 API fields only
    details_table.add_row("Home Region", format_value(connection.get("connection_region")))

    # Active and inactive regions
    if active_regions := connection.get("active_regions"):
        details_table.add_row("Active Regions", format_value(active_regions))
    if inactive_regions := connection.get("inactive_regions"):
        details_table.add_row("Inactive Regions", format_value(inactive_regions))

    # Boolean flags - use enhanced boolean formatting
    details_table.add_row("Enabled", format_value(connection.get("enabled", True)))
    details_table.add_row("Cost Connection", format_value(connection.get("is_cost_connection", False)))
    details_table.add_row("Metrics Enabled", format_value(connection.get("metrics_enabled", False)))
    details_table.add_row("Resources Enabled", format_value(connection.get("resources_enabled", False)))

    # Connection method - V4 API field only
    details_table.add_row("Connection Method", format_value(connection.get("provisioning_process")))

    # Features - V4 API fields only
    features = []
    if connection.get("resource_collector_configurations"):
        features.append("Resource Collection")
    if connection.get("auto_link_enabled", False):
        features.append("Auto-Link")

    details_table.add_row("Features", format_value(features) if features else "None")

    # AWS-specific identifiers - show all available ARNs and IDs
    if role_arn := connection.get("role_arn"):
        details_table.add_row("Role ARN", format_value(role_arn))
    if master_role_arn := connection.get("master_payer_role_arn"):
        details_table.add_row("Master Payer ARN", format_value(master_role_arn))
    if resource_role_arn := connection.get("resource_owner_role_arn"):
        details_table.add_row("Resource Owner ARN", format_value(resource_role_arn))
    if external_id := connection.get("external_id"):
        details_table.add_row("External ID", format_value(external_id))

    # Show auto-link information
    auto_link_enabled = connection.get("auto_link_enabled", False)
    details_table.add_row("Auto-Link Enabled", format_value(auto_link_enabled))
    if auto_link := connection.get("auto_link"):
        if auto_link:  # Only show if not empty dict
            details_table.add_row("Auto-Link Config", format_value(auto_link))

    # Show 30-day spend if available
    if spend := connection.get("last_30_days_billed_spend"):
        details_table.add_row("30-Day Spend", f"${float(spend):,.2f}" if spend else "N/A")

    # Database-specific identifiers - show if present
    if connection.get("PK"):
        details_table.add_row("Primary Key", format_value(connection.get("PK")))
    if connection.get("SK"):
        details_table.add_row("Sort Key", format_value(connection.get("SK")))
    if connection.get("ttl"):
        details_table.add_row("TTL", format_value(connection.get("ttl")))
    if connection.get("type"):
        details_table.add_row("Connection Type", format_value(connection.get("type")))
    if connection.get("record_sources"):
        details_table.add_row("Record Sources", format_value(connection.get("record_sources")))
    if connection.get("version_created"):
        details_table.add_row("Version Created", format_value(connection.get("version_created")))

    # Permission issues with proper formatting
    permission_errors = connection.get("permission_errors", [])
    if permission_errors:
        details_table.add_row("Permission Errors", "[red]Yes[/]")
        details_table.add_row("Error Details", format_value(permission_errors))
    else:
        details_table.add_row("Permission Errors", "[green]None[/]")

    console.print(details_table)

    # Add link to web UI
    console.print(
        f"\n[cyan]Web Console:[/] [link=https://app.cloudzero.com?organization_id={org_id}&connection_id={connection_id}]https://app.cloudzero.com?organization_id={org_id}&connection_id={connection_id}[/link]\n"
    )


def handle_info_command(arguments, organization_data=None):
    """Main handler for the info command."""
    entity_type = "org" if arguments.get("org") else "connection"
    id_or_name = arguments.get("<ID-or-NAME>")

    # Check if we're dealing with a connection ID
    if entity_type == "connection" or looks_like_a_connection_id(id_or_name):
        if entity_type == "org" and looks_like_a_connection_id(id_or_name):
            console.print(
                "[yellow]Warning:[/] The ID you provided looks like a connection ID, but you used the 'org' command. Switching to connection info."
            )
            entity_type = "connection"

        if entity_type == "connection":
            # Display connection info
            display_connection_info(arguments, id_or_name, organization_data)

    else:
        # If organization_data is not already provided, get it now
        if not organization_data:
            # Only fetch if we don't already have the data
            organization_data = get_organization_data(id_or_name, arguments)

        if not organization_data:
            # Show friendly message about organization not found with data freshness info
            console.print("\n[yellow]Organization Not Found[/]")
            console.print(f"No organization found with ID or name '[cyan]{id_or_name}[/]'")

            # Get data freshness information
            try:
                from src.api.v4_system import get_materialization_stats

                stats = get_materialization_stats(debug=arguments.get("--debug", False))
                if stats:
                    # Show when data was last refreshed
                    if timestamp := stats.get("completed_at") or stats.get("last_updated"):
                        console.print(
                            f"\n[dim]CloudZero is working with the latest data (last refresh: {timestamp})[/]"
                        )

                    # Show how many organizations are available
                    if org_count := stats.get("organizations_with_summaries"):
                        console.print(f"[dim]There are currently {org_count} organizations in the system[/]")
                    elif org_written := stats.get("organizations_written"):
                        # Handle array format - sum if it's a list
                        if isinstance(org_written, list):
                            total_orgs = sum(int(x) for x in org_written if str(x).isdigit())
                            console.print(f"[dim]There are currently {total_orgs} organizations in the system[/]")
                        else:
                            console.print(f"[dim]There are currently {org_written} organizations in the system[/]")

            except Exception:
                # Don't break if stats call fails
                console.print("\n[dim]CloudZero is working with the latest available data[/]")

            console.print("\n[cyan]💡 Try:[/]")
            console.print("  • [white]czops org list[/] - to see all available organizations")
            console.print(f"  • [white]czops org list {id_or_name}[/] - to search by partial name")
            console.print("  • Check the spelling of the organization name or ID")
            return

        # Display organization info
        display_organization_info(arguments, organization_data)
