"""GCP-specific validators for MCA SDK.

Shared validation functions for GCP resources to avoid circular dependencies.
"""

import re


def validate_gcp_project_id(project_id: str) -> None:
    """Validate GCP project ID format (simple or domain-scoped).

    GCP project IDs can be:
    1. Simple format: 'my-project' (6-30 chars, lowercase alphanumeric + hyphens)
    2. Domain-scoped format: 'example.com:my-project' (domain prefix + colon + simple ID)

    REGRESSION FIX: Previous implementation rejected domain-scoped IDs used by
    enterprise customers (e.g., "example.com:my-project"). This blocked valid GCP
    project IDs and prevented enterprise adoption.

    Simple format requirements:
    - Be 6-30 characters long
    - Start with a lowercase letter
    - Contain only lowercase letters, digits, and hyphens
    - Not end with a hyphen

    Domain-scoped format requirements:
    - Domain part: lowercase alphanumeric + dots/hyphens
    - ID part: follows simple format requirements

    Args:
        project_id: Project ID to validate

    Raises:
        ValueError: If project_id format is invalid
    """
    if not project_id:
        raise ValueError("project_id cannot be empty")

    # Check for domain-scoped format (domain:project-id)
    if ":" in project_id:
        # Split on rightmost colon to handle nested domains (example.com:google.com:my-project)
        # The ID is always after the last colon
        last_colon_idx = project_id.rfind(":")
        domain = project_id[:last_colon_idx]
        simple_id = project_id[last_colon_idx + 1 :]

        if not domain or not simple_id:
            raise ValueError("Domain-scoped ID must have format 'domain:project-id'")

        # Validate domain (basic check - has valid chars and colons for nested domains)
        if not re.match(r"^[a-z0-9.:-]+$", domain):
            raise ValueError(f"Invalid domain in project_id: {domain}")

        # Validate simple ID part
        project_id = simple_id

    # Validate simple format (or ID portion of domain-scoped)
    if len(project_id) < 6 or len(project_id) > 30:
        raise ValueError(f"project_id must be 6-30 characters, got {len(project_id)}")

    if not re.match(r"^[a-z][a-z0-9-]*$", project_id):
        raise ValueError(
            "project_id must start with lowercase letter and contain only "
            "lowercase letters, digits, and hyphens"
        )

    if project_id.endswith("-"):
        raise ValueError("project_id cannot end with a hyphen")
