# Copyright (c) CloudZero - ALL RIGHTS RESERVED - PROPRIETARY AND CONFIDENTIAL
# Unauthorized copying of this file and/or project, via any medium is strictly prohibited.
# Direct all questions to legal@cloudzero.com

import logging
from typing import Any

from rich.console import Console
from rich.progress import Progress, Task

from src.api.v4_connections import get_connections_for_org
from src.constants import NO_ACCOUNT_NAME, NO_ORG_NAME

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


def _fetch_org_connections(
    arguments: dict[str, Any], organization_data: dict[str, Any], progress: Progress, task: Task
) -> dict[str, Any]:
    """Fetch connections for multiple organizations."""
    connection_data = {}
    total_orgs = len(organization_data)

    progress.update(task, total=total_orgs, description="Fetching organization connections...")

    for idx, (cz_org_id, org_info) in enumerate(organization_data.items(), 1):
        org_name = org_info.get("organization_name", NO_ORG_NAME)

        progress.update(task, description=f"Fetching data for {org_name}", status=f"[{idx}/{total_orgs}]")

        try:
            connections_list = get_connections_for_org(cz_org_id, debug=arguments.get("--debug", False))
            # Convert to the expected format for backward compatibility
            org_connections = {}
            for conn in connections_list:
                org_connections[conn.connection_id] = conn.model_dump()

            connection_data[cz_org_id] = org_connections
            status = f"Retrieved {len(connections_list)} connections (fresh from v4 API)"
            progress.update(task, status=status)

        except Exception as error:
            console.print(f"[red]Error fetching connections for {org_name}: {error}")
            continue

        progress.advance(task)

    return connection_data


def _fetch_single_connection(arguments: dict[str, Any], progress: Progress, task: Task) -> dict[str, Any]:
    """Fetch a single connection by ID."""
    connection_id = arguments["<ID-or-NAME>"]

    progress.update(task, description=f"Fetching connection {connection_id}", status="In progress...")

    try:
        from src.api.v4_connections import get_connection

        connection = get_connection(connection_id, debug=arguments.get("--debug", False))

        # Convert to the expected nested format for backward compatibility
        # Determine the organization ID from the connection
        org_id = connection.cz_organization_id
        connection_data = {org_id: {connection_id: connection.model_dump()}}

        status = "Retrieved 1 connection (fresh from v4 API)"
        progress.update(task, status=status)

        return connection_data

    except Exception as error:
        console.print(f"[red]Error fetching connection {connection_id}: {error}")
        return {}
    finally:
        progress.advance(task)


def _format_connection_data(connection: dict[str, Any]) -> dict[str, Any]:
    """Format connection data for display or export."""
    return {
        "connection_id": connection.get("id"),
        "account_name": connection.get("connection_name", NO_ACCOUNT_NAME),
        "cloud_id": connection.get("connection_id"),
        "status": _get_connection_status(connection),
        "type": _get_connection_type(connection),
        "provider": connection.get("provider", "unknown"),
        "created": connection.get("created_on"),
        "last_updated": connection.get("last_seen"),
        "health": _get_connection_health(connection),
    }


def _get_connection_status(connection: dict[str, Any]) -> str:
    """Get formatted connection status."""
    if not connection.get("is_connected"):
        return "[red]Disconnected[/]"
    return "[yellow]Partial[/]" if connection.get("permission_errors") else "[green]Connected[/]"


def _get_connection_type(connection: dict[str, Any]) -> str:
    """Get formatted connection type."""
    if "COST" in connection.get("connection_types", []):
        return "[blue]Payer[/]"
    return "[cyan]Resource[/]"


def _get_connection_health(connection: dict[str, Any]) -> str:
    """Get formatted connection health status."""
    if connection.get("is_healthy"):
        return "[green]✓[/]"
    return "[red]✗[/]"


class ConnectionError(Exception):
    """Custom exception for connection-related errors."""

    pass


def handle_connection_error(error: Exception, context: str) -> None:
    """Handle connection-related errors consistently."""
    error_message = f"Error during {context}: {str(error)}"
    console.print(f"[red]{error_message}[/]")

    # Log the error (assuming you have a logging setup)
    logging.error(error_message, exc_info=True)

    # You might want to add additional error handling logic here
    if isinstance(error, ConnectionError | IOError):
        console.print("[yellow]Network or I/O error detected. Please check your connection.[/]")
    elif isinstance(error, KeyError):
        console.print("[yellow]Data format error detected. Please check your input data.[/]")
