# Copyright (c) 2022 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 src.api.v4_connections import get_connections_for_org, update_connection
from src.exceptions import APIError
from src.utils.console import eprint


def enable_resource_collection(
    organization_id: str, ignore_connection_ids: set[str] | None = None, arguments: dict | None = None
) -> bool:
    """Enable resource collection for connections in an organization."""
    return _configure_resource_collection(organization_id, True, ignore_connection_ids, arguments)


def disable_resource_collection(
    organization_id: str, ignore_connection_ids: set[str] | None = None, arguments: dict | None = None
) -> bool:
    """Disable resource collection for connections in an organization."""
    return _configure_resource_collection(organization_id, False, ignore_connection_ids, arguments)


def _configure_resource_collection(
    organization_id: str, enable: bool, ignore_connection_ids: set[str] | None = None, arguments: dict | None = None
) -> bool:
    """Configure resource collection for connections in an organization."""
    if ignore_connection_ids is None:
        ignore_connection_ids = set()

    debug = arguments.get("--debug", False) if arguments else False

    try:
        # Get all connections for the organization using V4 API
        connections = get_connections_for_org(organization_id, debug=debug)
    except APIError as e:
        eprint(f"ERROR: Failed to get connections for organization {organization_id}: {e}")
        return False

    if not connections:
        eprint(f"No connections found for organization {organization_id}")
        return False

    verb = "Enabling" if enable else "Disabling"
    past_tense = "Enabled" if enable else "Disabled"

    # Get organization name from first connection
    org_name = connections[0].connection_name or "Unknown"
    print(f"{verb} resource metadata collection for {org_name} ({organization_id})")

    success_count = 0
    failed_connections = []

    for connection in connections:
        connection_id = connection.connection_id

        if connection_id not in ignore_connection_ids:
            try:
                # Use V4 connection update API
                result = update_connection(connection_id, payload={"resource_collector_enabled": enable}, debug=debug)

                if result.success:
                    print(f" {connection_id:25} {past_tense.upper()}")
                    success_count += 1
                else:
                    print(f" {connection_id:25} FAILED to {past_tense.upper()}")
                    failed_connections.append(connection_id)

            except (APIError, Exception) as error:
                eprint(f"ERROR: {verb} resource metadata collection for {connection_id} failed: {error}")
                failed_connections.append(connection_id)
        else:
            print(f" {connection_id:25} SKIPPED")

    if failed_connections:
        eprint(f"\nFailed to {verb.lower()} resource collection for {len(failed_connections)} connections:")
        for conn_id in failed_connections:
            eprint(f"  - {conn_id}")
        return False

    print(f"\nSuccessfully {past_tense.lower()} resource collection for {success_count} connections")
    return success_count > 0


def status_resource_collection(organization_id: str, arguments: dict | None = None) -> bool:
    """Display resource collection status for an organization with improved formatting."""
    from rich.console import Console
    from rich.panel import Panel
    from rich.table import Table, box

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

    try:
        # Get all connections for the organization using V4 API
        connections = get_connections_for_org(organization_id, debug=debug)
    except APIError as e:
        eprint(f"ERROR: Failed to get connections for organization {organization_id}: {e}")
        return False

    if not connections:
        eprint(f"No connections found for organization {organization_id}")
        return False

    # Extract organization name from the first connection
    org_name = connections[0].connection_name or "Unknown"

    # Check which connections have resource collection enabled
    enabled_connections = []
    disabled_connections = []

    for connection in connections:
        connection_data = {
            "id": connection.connection_id,
            "name": connection.connection_name or "Unknown",
            "type": getattr(connection, "account_type", "Unknown"),  # Legacy field
            "provider": connection.cloud_provider,
        }

        # Check if resource collection is enabled (from legacy field)
        if hasattr(connection, "resources_enabled") and connection.resources_enabled:
            enabled_connections.append(connection_data)
        else:
            # Check legacy field name in raw data
            connection_dict = connection.model_dump()
            if connection_dict.get("resource_collector_enabled", False):
                enabled_connections.append(connection_data)
            else:
                disabled_connections.append(connection_data)

    # Create header
    header_text = f"Resource Collection Status for {org_name} ({organization_id})"
    console.print(Panel(header_text, style="bold cyan", title_align="left"))

    # Create summary table
    summary = Table.grid(padding=1)
    summary.add_column(style="blue", justify="left")
    summary.add_column(style="green", justify="left")

    total_connections = len(connections)
    summary.add_row("Organization:", f"{org_name} ({organization_id})")
    summary.add_row(
        "Total Connections:",
        f"{total_connections} ({len(enabled_connections)} enabled, {len(disabled_connections)} disabled)",
    )

    # Calculate percentage
    enabled_percentage = 0
    if total_connections > 0:
        enabled_percentage = (len(enabled_connections) / total_connections) * 100

    summary.add_row("Resource Collection Coverage:", f"{enabled_percentage:.1f}% of connections")
    console.print(Panel(summary, border_style="blue", title="Summary", title_align="left"))

    # Create tables for enabled and disabled connections
    if enabled_connections:
        enabled_table = Table(
            title=f"Enabled Connections ({len(enabled_connections)})",
            box=box.ROUNDED,
            title_style="bold green",
            title_justify="left",
            show_header=True,
            header_style="bold white",
        )

        enabled_table.add_column("Connection ID", style="cyan", justify="left")
        enabled_table.add_column("Connection Name", justify="left")
        enabled_table.add_column("Type", style="blue", justify="left")
        enabled_table.add_column("Provider", style="magenta", justify="left")

        for conn in sorted(enabled_connections, key=lambda x: x["id"]):
            enabled_table.add_row(conn["id"], conn["name"], conn["type"], conn["provider"])

        console.print(enabled_table)

    if disabled_connections:
        disabled_table = Table(
            title=f"Disabled Connections ({len(disabled_connections)})",
            box=box.ROUNDED,
            title_style="bold red",
            title_justify="left",
            show_header=True,
            header_style="bold white",
        )

        disabled_table.add_column("Connection ID", style="cyan", justify="left")
        disabled_table.add_column("Connection Name", justify="left")
        disabled_table.add_column("Type", style="blue", justify="left")
        disabled_table.add_column("Provider", style="magenta", justify="left")

        for conn in sorted(disabled_connections, key=lambda x: x["id"]):
            disabled_table.add_row(conn["id"], conn["name"], conn["type"], conn["provider"])

        console.print(disabled_table)
    else:
        console.print("[green]All connections have resource collection enabled[/]")

    return True


def functions(arguments: dict, organization_data: dict) -> bool | None:
    """Entry point for resource collection commands."""
    # Guard against a None/empty lookup result; get_organization_data already messaged the user.
    if not organization_data:
        return None
    for organization_id, _details in organization_data.items():
        try:
            if arguments["enable"]:
                result = enable_resource_collection(organization_id, arguments=arguments)
            elif arguments["disable"]:
                result = disable_resource_collection(organization_id, arguments=arguments)
            elif arguments["status"]:
                result = status_resource_collection(organization_id, arguments=arguments)
            else:
                eprint("ERROR: Unsupported resource collection command")
                sys.exit(-1)

            return result

        except APIError as e:
            eprint(f"ERROR: Resource collection command failed: {e}")
            return False
        except Exception as e:
            eprint(f"ERROR: Unexpected error: {e}")
            return False

    return None
