# Copyright (c) 2020 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 sys

from rich import box
from rich.columns import Columns
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich.text import Text

# Initialize Rich console
console = Console()

from src.api.v4_connections import get_connection, update_connection
from src.api.v4_healthcheck import get_connection_healthcheck
from src.utils.console import confirm, eprint, get_choice, yes_or_no


def update_and_refetch(connection_id: str, payload: dict) -> dict:
    """Update connection and refetch to get complete details."""
    update_connection(connection_id, payload=payload)
    updated_connection = get_connection(connection_id)
    return updated_connection.model_dump()


def display_connection_health_summary(healthcheck_result: dict, connection_id: str, account_name: str, org_name: str) -> None:
    """
    Display a visually appealing health summary for a connection.

    Args:
        healthcheck_result: The healthcheck response dictionary from V4 API
        connection_id: The connection identifier
        account_name: The account/connection name
        org_name: The organization name
    """
    # Handle both V4 API format (status field) and legacy format (is_healthy field)
    status = healthcheck_result.get("status", "unknown")
    is_healthy = healthcheck_result.get("is_healthy", status.lower() == "healthy" if status else False)
    status = status.upper() if status else "UNKNOWN"
    overall_score = healthcheck_result.get("overall_score")
    summary = healthcheck_result.get("summary", {})
    checks = healthcheck_result.get("checks", [])

    # Determine overall health color and icon
    if is_healthy or status == "HEALTHY":
        status_color = "green"
        status_icon = "✅"
        border_style = "green"
    elif status in ["DEGRADED", "WARNING"]:
        status_color = "yellow"
        status_icon = "⚠️"
        border_style = "yellow"
    else:
        status_color = "red"
        status_icon = "❌"
        border_style = "red"

    # Create header panel with overall status
    header_text = Text()
    header_text.append(f"{status_icon}  Connection Health Status: ", style="bold")
    header_text.append(status, style=f"bold {status_color}")
    if overall_score is not None:
        header_text.append(f" ({overall_score:.1f}/100)", style=f"dim {status_color}")

    header_panel = Panel(
        header_text,
        title=f"[bold white]{org_name} - {account_name}[/bold white]",
        subtitle=f"[dim]ID: {connection_id}[/dim]",
        border_style=border_style,
        box=box.ROUNDED,
        padding=(0, 2),
    )
    console.print()
    console.print(header_panel)

    # Create summary statistics table
    if summary:
        stats_table = Table(box=box.SIMPLE, show_header=False, padding=(0, 2), collapse_padding=True)
        stats_table.add_column("Metric", style="dim", no_wrap=True)
        stats_table.add_column("Value", justify="right")

        total_checks = summary.get("total_checks", 0)
        healthy_count = summary.get("healthy_count", 0)
        degraded_count = summary.get("degraded_count", 0)
        unhealthy_count = summary.get("unhealthy_count", 0)

        stats_table.add_row("Total Checks", str(total_checks))
        if healthy_count > 0:
            stats_table.add_row("Healthy", f"[green]{healthy_count}[/green]")
        if degraded_count > 0:
            stats_table.add_row("Degraded", f"[yellow]{degraded_count}[/yellow]")
        if unhealthy_count > 0:
            stats_table.add_row("Unhealthy", f"[red]{unhealthy_count}[/red]")

        console.print(stats_table)
        console.print()

    # Display individual check details
    if checks:
        checks_table = Table(
            title="Health Check Details",
            box=box.ROUNDED,
            show_header=True,
            header_style="bold cyan",
            padding=(0, 1),
        )

        checks_table.add_column("Check", style="cyan", no_wrap=False)
        checks_table.add_column("Status", justify="center", width=12)
        checks_table.add_column("Message", style="dim")

        for check in checks:
            check_name = check.get("name", "Unknown")
            check_status = check.get("status", "unknown").upper()
            check_message = check.get("message", "")

            # Determine check status color and icon
            if check_status == "HEALTHY":
                check_icon = "✓"
                check_color = "green"
            elif check_status in ["DEGRADED", "WARNING"]:
                check_icon = "⚠"
                check_color = "yellow"
            else:
                check_icon = "✗"
                check_color = "red"

            status_display = f"[{check_color}]{check_icon} {check_status}[/{check_color}]"
            checks_table.add_row(check_name, status_display, check_message or "—")

        console.print(checks_table)
        console.print()

    # Show warning message if unhealthy
    if not is_healthy and status not in ["HEALTHY", "DEGRADED"]:
        warning_panel = Panel(
            "[bold yellow]⚠️  Proceed with caution - some health checks are failing[/bold yellow]\n"
            "Review the health check details above before making configuration changes.",
            border_style="yellow",
            box=box.ROUNDED,
        )
        console.print(warning_panel)
        console.print()


def functions(arguments, _organization_data=None):
    result = "Dry Run"
    connection_id = arguments.get("<ID>")
    print(f"Fetching connection information for {connection_id}...\n")

    try:
        connection_record = get_connection(connection_id)
        # Convert to dictionary format for backward compatibility
        account_record = connection_record.model_dump()
    except Exception as e:
        eprint(f"ERROR: Failed to get connection {connection_id}: {e}")
        sys.exit(-1)

    # Handle potential missing fields
    org_name = account_record.get("cz_organization_name", account_record.get("organization_name", "Unknown"))
    account_name = account_record.get("connection_name", account_record.get("cz_account_name", "Unknown"))

    print(f"Ready to configure {org_name.capitalize()}: {account_name.capitalize()} ({connection_id})")

    # Check for non-interactive billing options
    billing_enable = arguments.get("--billing-enable")
    billing_disable = arguments.get("--billing-disable")
    billing_cur = arguments.get("--billing-cur")
    force = arguments.get("--force", False)

    # Always configure BILLING since UCA has been removed
    feature = "BILLING"
    print(f"Configuring {feature}")

    # Skip healthcheck in non-interactive mode if force is specified
    if force and (billing_enable or billing_disable):
        healthcheck_result = {"is_healthy": True, "cur_health": {}}
        cur_health = {}
    else:
        console.print("\n[cyan]→ Verifying connection health before proceeding...[/cyan]")
        # Use V4 healthcheck API
        try:
            healthcheck_response = get_connection_healthcheck(connection_id)
            # Convert to dictionary format for backward compatibility
            healthcheck_result = healthcheck_response.model_dump()

            # Extract CUR health from checks array (V4 API structure)
            cur_health = {}
            checks = healthcheck_result.get("checks", [])
            for check in checks:
                if check.get("name") == "cur_and_data_collection":
                    check_details = check.get("details", {})
                    visible_curs = check_details.get("visible_curs", [])

                    # Convert visible_curs list to cur_health dict format
                    for cur in visible_curs:
                        cur_name = cur.get("name")
                        if cur_name:
                            # Map V4 response to expected format
                            cur_health[cur_name] = {
                                "healthy": cur.get("is_healthy", False),
                                "bucket_healthy": cur.get("is_accessible", False),
                                "has_warnings": cur.get("status") == "degraded",
                                "reason": cur.get("access_error") or "CUR correctly configured",
                            }
                    break

            healthcheck_result["cur_health"] = cur_health

            # Set is_healthy based on status for backward compatibility
            if "is_healthy" not in healthcheck_result:
                healthcheck_result["is_healthy"] = healthcheck_result.get("status", "").lower() == "healthy"
        except Exception as e:
            eprint(f"Error fetching healthcheck: {e}")
            healthcheck_result = {"is_healthy": False, "status": "error", "cur_health": {}}
            cur_health = {}

    # Display health summary regardless of health status
    display_connection_health_summary(healthcheck_result, connection_id, account_name, org_name)

    # For non-interactive enable/disable, we don't need CUR metadata
    if (billing_enable or billing_disable) and force:
        # Handle enable/disable directly
        billing_action = "enable" if billing_enable else "disable"

        # Check current state
        is_currently_enabled = account_record.get("is_cost_connection", False)

        if billing_action == "enable" and is_currently_enabled:
            print(f"Connection {connection_id} is already enabled as a master payer account")
            sys.exit(0)
        elif billing_action == "disable" and not is_currently_enabled:
            print(f"Connection {connection_id} is already disabled as a master payer account")
            sys.exit(0)

        payload = {"is_cost_connection": billing_action == "enable"}
        console.print(f"\n[bold]{billing_action.capitalize()[:-1]}ing {connection_id} as a payer account...[/bold]")

        try:
            result = update_connection(connection_id, payload=payload)
            # Refetch connection to get updated details
            updated_connection = get_connection(connection_id)
            updated_record = updated_connection.model_dump()

            # Success indicator
            action_past = "enabled" if billing_action == "enable" else "disabled"
            console.print(f"\n[bold green]✅ SUCCESS[/bold green] - Account successfully {action_past} as master payer\n")

            # Show account details
            status_table = Table(title="Account Billing Status", box=box.ROUNDED)
            status_table.add_column("Property", style="dim")
            status_table.add_column("Value")

            is_cost = updated_record.get("is_cost_connection", False)
            status_color = "green" if is_cost else "red"
            status_text = "Enabled" if is_cost else "Disabled"

            status_table.add_row("Master Payer Status", f"[{status_color}]{status_text}[/{status_color}]")
            status_table.add_row("Organization ID", updated_record.get("cz_organization_id", "N/A"))
            status_table.add_row("Organization", org_name)
            status_table.add_row("Account Name", account_name)
            status_table.add_row("Connection ID", connection_id)

            # Get CUR info from connection_details
            conn_details = updated_record.get("connection_details", {})
            cur_data = conn_details.get("cur_data", {})
            if cur_data.get("bucket_name"):
                status_table.add_row("Billing Bucket", cur_data["bucket_name"])
            if cur_data.get("report_name"):
                status_table.add_row("Current CUR", cur_data["report_name"])

            console.print(status_table)
        except Exception as e:
            # Failure indicator
            console.print(f"\n[bold red]❌ FAILED[/bold red] - Failed to {billing_action} master payer account\n")
            error_panel = Panel(str(e), title="[bold red]Error Details[/bold red]", border_style="red", expand=False)
            console.print(error_panel)
        return

    # V4 API stores CUR data in connection_details.cur_configurations, legacy uses cur_metadata
    connection_details = account_record.get("connection_details", {})
    cur_metadata = connection_details.get("cur_configurations") or account_record.get("cur_metadata", {})

    if cur_metadata:
        # V4 API stores provider as "provider", legacy as "cloud_provider"
        provider = account_record.get("provider") or account_record.get("cloud_provider", "")
        if provider.lower() != "aws":
            eprint(" - Only AWS account billing connections are currently supported by CZOPS")
            sys.exit()

        # Show current CUR configuration if set
        # V4 API stores cur_data in connection_details
        cur_data = connection_details.get("cur_data") or {}
        current_cur = cur_data.get("report_name") or account_record.get("master_payer_billing_report_name")

        if current_cur:
            console.print("\n[bold cyan]Current CUR Configuration:[/bold cyan]")
            console.print(f"  • Report Name: [bold]{current_cur}[/bold]")
            bucket = cur_data.get("bucket_name") or account_record.get("master_payer_billing_bucket_name", "N/A")
            bucket_path = cur_data.get("bucket_path") or account_record.get("master_payer_billing_bucket_path", "N/A")
            console.print(f"  • S3 Bucket: {bucket}")
            console.print(f"  • S3 Path: {bucket_path}")
        else:
            console.print("\n[bold yellow]⚠️  No CUR currently configured[/bold yellow]")

        console.print(f"\n[bold]Found {len(cur_metadata)} AWS CUR Configuration(s)[/bold]\n")

        # Create a table for CUR configurations
        table = Table(
            title="CUR Configurations Overview",
            box=box.ROUNDED,
            show_header=True,
            header_style="bold cyan",
            title_style="bold white",
            padding=(0, 1),
            expand=True,  # Allow table to expand to fit content
        )

        # Add columns (no width constraints to prevent truncation)
        table.add_column("#", style="dim", width=3)
        table.add_column("Report Name", style="cyan", no_wrap=True)
        table.add_column("Compatible", justify="center")
        table.add_column("Reachable", justify="center")
        table.add_column("Format")
        table.add_column("Frequency")
        table.add_column("S3 Location", style="dim", no_wrap=True)

        compatible_CURs = {}
        healthy_CURs = {}

        for idx, (report_name, report) in enumerate(cur_metadata.items(), 1):
            # Skip if it's not a dictionary (e.g., metadata field)
            if not isinstance(report, dict):
                continue

            # Check health status - handle missing cur_health data
            cur_report_health = cur_health.get(report_name, {}) if cur_health else {}
            is_healthy = cur_report_health.get("healthy", False)
            bucket_healthy = cur_report_health.get("bucket_healthy", False)
            has_warnings = cur_report_health.get("has_warnings", False)

            # Highlight report name if it's the current one or if it's healthy
            report_style = "green bold" if report_name == current_cur else ("cyan" if is_healthy else "bright_white")

            # Display health status - backend now owns the definition of "compatible"
            # Green (healthy) = all required rules pass
            # Yellow (warning) = required rules pass but has warnings
            # Red (unhealthy) = required rules failed
            if is_healthy and not has_warnings:
                compatible = "[green bold]YES[/green bold]"
            elif is_healthy and has_warnings:
                compatible = "[yellow bold]WARN[/yellow bold]"
            else:
                compatible = "[red bold]NO[/red bold]"
            reachable = yes_or_no(
                bucket_healthy,
                yes_color="green",
                no_color="red",
                format="UPPER",
            )

            # Track healthy and compatible CURs separately
            # Healthy CURs: All required rules pass (may have warnings about recommended rules)
            # Compatible CURs: Same as healthy - only CURs that pass all required rules
            if is_healthy:
                healthy_CURs[report_name] = report
                compatible_CURs[report_name] = report

            # Format S3 location
            s3_location = f"s3://{report.get('S3Bucket', 'Unknown')}/{report.get('S3Prefix', '')}"

            # Add row to table with highlighting for current CUR
            current_marker = " (CURRENT)" if report_name == current_cur else ""
            table.add_row(
                str(idx),
                f"[{report_style}]{report_name}{current_marker}[/{report_style}]",
                f"[bold]{compatible}[/bold]",
                f"[bold]{reachable}[/bold]",
                report.get("Format", "Unknown"),
                report.get("TimeUnit", "Unknown"),
                s3_location,
            )

        console.print(table)

        # Show summary of healthy and compatible CURs
        if healthy_CURs:
            console.print(f"\n[bold green]✅ {len(healthy_CURs)} Healthy CUR(s) Available:[/bold green]")
            for report_name in healthy_CURs:
                report = healthy_CURs[report_name]
                console.print(f"  • [green]{report_name}[/green]: {report.get('Format')} ({report.get('ReportVersioning')})")

        if compatible_CURs and len(compatible_CURs) > len(healthy_CURs):
            console.print(f"\n[bold yellow]⚠️  {len(compatible_CURs) - len(healthy_CURs)} Potentially Compatible CUR(s):[/bold yellow]")
            for report_name in compatible_CURs:
                if report_name not in healthy_CURs:
                    report = compatible_CURs[report_name]
                    console.print(f"  • [yellow]{report_name}[/yellow]: {report.get('Format')} ({report.get('ReportVersioning')})")

        # Exit if no healthy CURs are available
        if not healthy_CURs:
            console.print()
            error_panel = Panel(
                "[bold red]No healthy CUR configurations found![/bold red]\n\n"
                "All available CURs have health check failures that prevent them from being used.\n"
                "Please review the health check results above and fix the issues before reconfiguring.\n\n"
                "[dim]Common issues:[/]\n"
                "  • Invalid format (must be textORcsv, not Parquet)\n"
                "  • Invalid compression (must be GZIP)\n"
                "  • S3 bucket access denied\n"
                "  • Wrong report versioning (must be OVERWRITE_REPORT)",
                title="[bold red]❌ Cannot Reconfigure[/bold red]",
                border_style="red",
                box=box.ROUNDED,
            )
            console.print(error_panel)
            console.print()
            sys.exit(1)

        console.print()  # Add spacing before menu

        # Handle non-interactive mode
        if billing_enable or billing_disable or billing_cur:
            if billing_enable and billing_disable:
                eprint("Error: Cannot specify both --billing-enable and --billing-disable")
                sys.exit(1)

            if billing_enable:
                billing_action = "enable"
            elif billing_disable:
                billing_action = "disable"
            elif billing_cur:
                billing_action = "change_cur"
        else:
            # Interactive mode
            action_text = account_record.get("is_cost_connection", False) and "disable" or "enable"
            billing_choices = [
                "Change CUR and Enable",
                f"{action_text.capitalize()} Connection",
                "Do nothing and exit",
            ]
            choice = get_choice(billing_choices, "Billing Account Option")

            if choice == billing_choices[0]:
                billing_action = "change_cur"
            elif choice == billing_choices[1]:
                billing_action = action_text
            else:
                billing_action = "exit"

        if billing_action == "change_cur":
            print(f"OK, Reconfiguring billing connection for connection {connection_id}\n")

            # In non-interactive mode, find the CUR by name
            if billing_cur:
                desired_cur = None
                for cur_name, cur_data in healthy_CURs.items():
                    if cur_name == billing_cur:
                        desired_cur = cur_data
                        break

                if not desired_cur:
                    eprint(f"Error: CUR '{billing_cur}' not found in healthy CURs")
                    print("Available healthy CURs:")
                    for cur_name in healthy_CURs:
                        print(f"  - {cur_name}")
                    sys.exit(1)
            else:
                # Interactive mode - only show healthy CURs as options
                desired_cur = get_choice(healthy_CURs, "healthy CUR Configuration")

            if desired_cur and desired_cur.get("ReportName"):
                # Store previous configuration - handle both V4 and legacy formats
                previous_cur_name = current_cur or "None"
                previous_bucket = cur_data.get("bucket_name") or account_record.get("master_payer_billing_bucket_name", "None")
                previous_path = cur_data.get("bucket_path") or account_record.get("master_payer_billing_bucket_path", "None")

                payload = {
                    "master_payer_billing_bucket_name": desired_cur["S3Bucket"],
                    "master_payer_billing_bucket_path": f"{desired_cur['S3Prefix']}/{desired_cur['ReportName']}",
                    "is_cost_connection": True,
                    "master_payer_billing_report_name": desired_cur["ReportName"],
                }

                console.print(f"\n[bold]Updating connection settings to use CUR '[cyan]{desired_cur['ReportName']}[/cyan]'...[/bold]")

                try:
                    result = update_and_refetch(connection_id, payload)
                except Exception as e:
                    # Failure indicator
                    console.print("\n[bold red]❌ FAILED[/bold red] - Failed to update billing configuration\n")
                    error_panel = Panel(str(e), title="[bold red]Error Details[/bold red]", border_style="red", expand=False)
                    console.print(error_panel)
                    return

                # Display formatted result
                if result:
                    # Success indicator
                    console.print("\n[bold green]✅ SUCCESS[/bold green] - Billing configuration updated successfully\n")

                    # Create before/after comparison
                    before_table = Table(title="Previous Configuration", box=box.ROUNDED, title_style="bold red")
                    before_table.add_column("Setting", style="dim")
                    before_table.add_column("Value", style="red")
                    before_table.add_row("CUR Name", previous_cur_name)
                    before_table.add_row("S3 Bucket", previous_bucket)
                    before_table.add_row("S3 Path", previous_path)

                    after_table = Table(title="New Configuration", box=box.ROUNDED, title_style="bold green")
                    after_table.add_column("Setting", style="dim")
                    after_table.add_column("Value", style="green")
                    after_table.add_row("CUR Name", desired_cur["ReportName"])
                    after_table.add_row("S3 Bucket", desired_cur["S3Bucket"])
                    after_table.add_row("S3 Path", f"{desired_cur['S3Prefix']}/{desired_cur['ReportName']}")

                    # Display side by side
                    console.print(Columns([before_table, after_table], padding=2))

                    # Show key billing details
                    conn_details = result.get("connection_details", {})
                    cur_updated = conn_details.get("cur_data", {})
                    if cur_updated:
                        console.print("\n[bold]Account Billing Status:[/bold]")
                        console.print("  • Master Payer Account: [green]Enabled[/green]")
                        console.print(f"  • Organization ID: {result.get('cz_organization_id', 'N/A')}")
                        console.print(f"  • Organization: {org_name}")
                        console.print(f"  • Account Name: {account_name}")
                        console.print(f"  • Connection ID: {connection_id}")
                        console.print("  • Health Status: [green]Updated[/green]")
            else:
                print("Invalid choice, aborting")
        elif billing_action in ["enable", "disable"]:
            # Check current state
            is_currently_enabled = account_record.get("is_cost_connection", False)

            if billing_action == "enable" and is_currently_enabled:
                print(f"Connection {connection_id} is already enabled as a master payer account")
                if not force:
                    sys.exit(0)
            elif billing_action == "disable" and not is_currently_enabled:
                print(f"Connection {connection_id} is already disabled as a master payer account")
                if not force:
                    sys.exit(0)

            # Confirm action in interactive mode
            if not force and not (billing_enable or billing_disable):
                if not confirm(f"{billing_action.capitalize()} {connection_id} as a payer account?"):
                    print("Aborting, nothing changed")
                    sys.exit(0)

            payload = {"is_cost_connection": billing_action == "enable"}
            console.print(f"\n[bold]{billing_action.capitalize()[:-1]}ing {connection_id} as a payer account...[/bold]")

            try:
                result = update_and_refetch(connection_id, payload)
            except Exception as e:
                console.print(f"\n[bold red]❌ FAILED[/bold red] - Failed to {billing_action} master payer account\n")
                error_panel = Panel(str(e), title="[bold red]Error Details[/bold red]", border_style="red", expand=False)
                console.print(error_panel)
                return

            # Display formatted result
            if result:
                # Success indicator
                action_past = "enabled" if billing_action == "enable" else "disabled"
                console.print(f"\n[bold green]✅ SUCCESS[/bold green] - Account successfully {action_past} as master payer\n")

                # Show account details
                status_table = Table(title="Account Billing Status", box=box.ROUNDED)
                status_table.add_column("Property", style="dim")
                status_table.add_column("Value")

                is_cost = result.get("is_cost_connection", False)
                status_color = "green" if is_cost else "red"
                status_text = "Enabled" if is_cost else "Disabled"

                status_table.add_row("Master Payer Status", f"[{status_color}]{status_text}[/{status_color}]")
                status_table.add_row("Organization ID", result.get("cz_organization_id", "N/A"))
                status_table.add_row("Organization", org_name)
                status_table.add_row("Account Name", account_name)
                status_table.add_row("Connection ID", connection_id)

                conn_details = result.get("connection_details", {})
                cur_data_updated = conn_details.get("cur_data", {})
                if cur_data_updated.get("bucket_name"):
                    status_table.add_row("Billing Bucket", cur_data_updated["bucket_name"])
                if cur_data_updated.get("report_name"):
                    status_table.add_row("Current CUR", cur_data_updated["report_name"])

                console.print(status_table)
        elif billing_action == "exit":
            print("Aborting, nothing changed")
    else:
        # Even without CUR metadata, we can still enable/disable billing
        print(" - No CUR configurations found for this account")

        if not (billing_enable or billing_disable or billing_cur):
            # Interactive mode - offer to enable/disable
            action_text = account_record.get("is_cost_connection", False) and "disable" or "enable"
            billing_choices = [
                f"{action_text.capitalize()} Connection",
                "Do nothing and exit",
            ]
            choice = get_choice(billing_choices, "Billing Account Option")

            billing_action = action_text if choice == billing_choices[0] else "exit"

            # Handle the enable/disable action
            if billing_action in ["enable", "disable"]:
                # Check current state
                is_currently_enabled = account_record.get("is_cost_connection", False)

                if billing_action == "enable" and is_currently_enabled:
                    print(f"Connection {connection_id} is already enabled as a master payer account")
                    sys.exit(0)
                elif billing_action == "disable" and not is_currently_enabled:
                    print(f"Connection {connection_id} is already disabled as a master payer account")
                    sys.exit(0)

                # Confirm action
                if not confirm(f"{billing_action.capitalize()} {connection_id} as a payer account?"):
                    print("Aborting, nothing changed")
                    sys.exit(0)

                payload = {"is_cost_connection": billing_action == "enable"}
                console.print(f"\n[bold]{billing_action.capitalize()[:-1]}ing {connection_id} as a payer account...[/bold]")

                try:
                    result = update_and_refetch(connection_id, payload)
                except Exception as e:
                    console.print(f"\n[bold red]❌ FAILED[/bold red] - Failed to {billing_action} master payer account\n")
                    error_panel = Panel(str(e), title="[bold red]Error Details[/bold red]", border_style="red", expand=False)
                    console.print(error_panel)
                    return

                # Display formatted result (same as above)
                if result:
                    # Success indicator
                    action_past = "enabled" if billing_action == "enable" else "disabled"
                    console.print(f"\n[bold green]✅ SUCCESS[/bold green] - Account successfully {action_past} as master payer\n")

                    # Show account details
                    status_table = Table(title="Account Billing Status", box=box.ROUNDED)
                    status_table.add_column("Property", style="dim")
                    status_table.add_column("Value")

                    is_cost = result.get("is_cost_connection", False)
                    status_color = "green" if is_cost else "red"
                    status_text = "Enabled" if is_cost else "Disabled"

                    status_table.add_row("Master Payer Status", f"[{status_color}]{status_text}[/{status_color}]")
                    status_table.add_row("Organization ID", result.get("cz_organization_id", "N/A"))
                    status_table.add_row("Organization", org_name)
                    status_table.add_row("Account Name", account_name)
                    status_table.add_row("Connection ID", connection_id)

                    console.print(status_table)
            else:
                print("Aborting, nothing changed")
