"""Cloud provider ID validation utilities."""

import re


def is_valid_cloud_provider_id(connection_id: str) -> bool:
    """Check if connection_id appears to be a valid cloud provider identifier.

    Valid patterns:
    - AWS: 12-digit number
    - Azure: UUID format (8-4-4-4-12 hex digits)
    - GCP: Alphanumeric with hyphens, typically project IDs
    - MongoDB Atlas: UUID format
    - Databricks: UUID format
    - Datadog: Alphanumeric identifiers

    Returns False for obvious non-cloud identifiers like "Amplitude PROD".
    """
    if not connection_id or not isinstance(connection_id, str):
        return False

    # Remove any whitespace
    connection_id = connection_id.strip()

    # Special case: Allow "None" as valid for view-based anomalies
    # These anomalies don't have a specific cloud account
    if connection_id.lower() == "none":
        return True

    # Check for other None-like values that are NOT valid
    if connection_id.lower() in ("null", "n/a", "na", ""):
        return False

    # AWS account ID pattern (12 digits)
    if re.match(r"^\d{12}$", connection_id):
        return True

    # UUID pattern (Azure subscriptions, MongoDB Atlas, Databricks, etc.)
    uuid_pattern = r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"
    if re.match(uuid_pattern, connection_id):
        return True

    # GCP project ID pattern (6-30 chars, lowercase letters, digits, hyphens)
    # Must start with a letter, can't end with hyphen
    gcp_pattern = r"^[a-z][a-z0-9-]{4,28}[a-z0-9]$"
    if re.match(gcp_pattern, connection_id):
        return True

    # Datadog account pattern (alphanumeric, may include underscores)
    # These are typically shorter identifiers
    datadog_pattern = r"^[a-zA-Z0-9_]{8,20}$"
    if re.match(datadog_pattern, connection_id):
        return True

    # Check for obvious non-cloud provider patterns
    # These are likely internal aliases or non-cloud identifiers

    # Contains spaces (like "Amplitude PROD")
    if " " in connection_id:
        return False

    # Title case with spaces or other human-readable names
    if re.match(r"^[A-Z][a-zA-Z\s]+$", connection_id):
        return False

    # Contains special characters that are unlikely in cloud IDs
    invalid_chars = [
        "!",
        "@",
        "#",
        "$",
        "%",
        "^",
        "&",
        "*",
        "(",
        ")",
        "=",
        "+",
        "[",
        "]",
        "{",
        "}",
        "|",
        "\\",
        ":",
        ";",
        '"',
        "'",
        "<",
        ">",
        "?",
        "/",
    ]
    if any(c in connection_id for c in invalid_chars):
        return False

    # If it doesn't match known patterns but also doesn't look obviously wrong,
    # we'll tentatively allow it (could be a new provider format)
    # But reject very short IDs (less than 8 chars) as they're unlikely to be valid
    return not len(connection_id) < 8


def validate_connection_ids(rows: list[dict]) -> tuple[list[dict], list[str]]:
    """Validate connection_ids in a list of rows.

    Args:
        rows: List of dictionaries containing 'connection_id' or 'account_id' fields

    Returns:
        Tuple of (valid_rows, warning_messages)
        - valid_rows: Rows with potentially valid connection_ids
        - warning_messages: List of warning messages for invalid connection_ids
    """
    valid_rows = []
    warnings = []

    for i, row in enumerate(rows, start=1):
        # Check both possible field names
        connection_id = row.get("connection_id") or row.get("account_id")

        if connection_id and not is_valid_cloud_provider_id(str(connection_id)):
            row_num = row.get("_row_num", i)
            warnings.append(
                f"Row {row_num}: connection_id '{connection_id}' may not be a valid cloud provider identifier"
            )

        valid_rows.append(row)

    return valid_rows, warnings


def suggest_fix_for_invalid_id(connection_id: str) -> str:
    """Suggest a fix for an invalid connection ID.

    Args:
        connection_id: The invalid connection ID

    Returns:
        A suggestion message for fixing the ID
    """
    # "None" is valid for view-based anomalies
    if connection_id.lower() == "none":
        return "'None' is valid for view-based anomalies without a specific cloud account"

    if " " in connection_id:
        return "Remove spaces or replace with a valid cloud provider account ID"

    if connection_id.lower() in ("null", "n/a"):
        return "Provide a valid cloud provider account ID (AWS account, Azure subscription, GCP project) or use 'None' for view-based anomalies"

    if re.match(r"^[A-Z][a-zA-Z\s]+$", connection_id):
        return "This appears to be a human-readable name. Replace with the actual cloud provider ID"

    return "Ensure this is a valid AWS account ID (12 digits), Azure subscription ID (UUID), or GCP project ID"
