# 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 datetime import datetime
from typing import Any
from urllib.parse import urlencode


def build_explorer_url(
    partition: str | None = None,
    date_selection: dict[str, Any] | None = None,
    filters: dict[str, Any] | None = None,
    view_id: str | None = None,
    granularity: str | None = None,
    show_right_flyout: str | None = None,
    referral: str | None = None,
) -> str:
    """
    Build a CloudZero Explorer URL with the specified parameters.

    This function replaces the resolve_link_mechanics function from notification-provider
    to generate CloudZero dashboard URLs without external dependencies.

    Args:
        partition: The active partition/group-by setting (e.g., 'resources', 'services')
        date_selection: Date range configuration containing:
            - 'date_range': 'Last 3 Days' | 'Last 7 Days' | 'Last 30 Days' | 'Last 90 Days' | 'Custom'
            - 'start_date': datetime - required if date_range is 'Custom'
            - 'end_date': datetime - required if date_range is 'Custom'
        filters: Dictionary of filter values to apply (e.g., {'accounts': '123456', 'services': 'ec2'})
        view_id: Set view state in explorer
        granularity: Time granularity - 'hourly' | 'daily'
        show_right_flyout: Right panel setting - 'events' | 'filters'
        referral: Referral tracking parameter

    Returns:
        Complete CloudZero Explorer URL as a string

    Examples:
        >>> build_explorer_url(
        ...     partition="resources",
        ...     date_selection={"date_range": "Last 7 Days"},
        ...     filters={"accounts": "123456789012"},
        ...     granularity="daily"
        ... )
        'https://app.cloudzero.com/explorer?partitions=resources&dateRange=Last+7+Days&accounts=123456789012&granularity=daily'
    """
    # Base CloudZero Explorer URL
    base_url = "https://app.cloudzero.com/explorer"

    # Initialize parameters dictionary
    params = {}

    # Add partition (mapped to 'partitions' parameter)
    if partition:
        params["partitions"] = partition

    # Add date selection parameters
    if date_selection:
        date_range = date_selection.get("date_range")
        if date_range:
            params["dateRange"] = date_range

            # For custom date ranges, add start and end dates
            if date_range == "Custom":
                start_date = date_selection.get("start_date")
                end_date = date_selection.get("end_date")

                if start_date:
                    # Convert datetime to ISO format with Z suffix
                    if isinstance(start_date, datetime):
                        params["startDate"] = start_date.strftime("%Y-%m-%dT%H:%M:%SZ")
                    else:
                        params["startDate"] = str(start_date)

                if end_date:
                    # Convert datetime to ISO format with Z suffix
                    if isinstance(end_date, datetime):
                        params["endDate"] = end_date.strftime("%Y-%m-%dT%H:%M:%SZ")
                    else:
                        params["endDate"] = str(end_date)

    # Add filters
    if filters:
        for key, value in filters.items():
            if value is not None:
                # Handle both string and list values
                if isinstance(value, list):
                    # Join list values with commas
                    params[key] = ",".join(str(v) for v in value)
                else:
                    params[key] = str(value)

    # Add optional parameters
    if view_id:
        params["viewId"] = view_id

    if granularity:
        params["granularity"] = granularity

    if show_right_flyout:
        params["showRightFlyout"] = show_right_flyout

    if referral:
        params["referral"] = referral

    # Build the complete URL
    if params:
        query_string = urlencode(params, safe=":,-")
        return f"{base_url}?{query_string}"
    else:
        return base_url


def resolve_link_mechanics(
    partition: str | None = None,
    date_selection: dict[str, Any] | None = None,
    filters: dict[str, Any] | None = None,
    view_id: str | None = None,
    granularity: str | None = None,
    show_right_flyout: str | None = None,
    referral: str | None = None,
) -> str:
    """
    Legacy function name compatibility wrapper for build_explorer_url.

    This function maintains the same interface as the notification-provider's
    resolve_link_mechanics function to ensure backward compatibility.

    Args:
        Same as build_explorer_url

    Returns:
        Complete CloudZero Explorer URL as a string
    """
    return build_explorer_url(
        partition=partition,
        date_selection=date_selection,
        filters=filters or {},
        view_id=view_id,
        granularity=granularity,
        show_right_flyout=show_right_flyout,
        referral=referral,
    )
