# 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
#

"""
V4 Resources API Client

This module provides a clean, modern interface for managing cloud resource data using the v4 API
with Okta authentication. This replaces legacy resource functions with:
- get_resource_information(org_id, resource_id) -> returns ResourceInfo object

NOTE: Previous functions get_resource_groups() and get_resource_projection() have been
removed as these endpoints are not documented in the V4 API specification and do not
exist in the backend. Only the single resource lookup endpoint is supported.
"""

from typing import Any

from pydantic import BaseModel, Field, ValidationError
from rich.console import Console

from src.api.authenticated import get_authenticated
from src.exceptions import APIError

console = Console()


# V4 Pydantic Models - Clean, modern API contract matching backend schema
class ResourceInfo(BaseModel):
    """Resource information response model matching V4 API schema."""

    # Core resource identification (matching V4 API response)
    organization_id: str = Field(..., description="Organization UUID")
    resource_id: str = Field(..., description="Resource identifier")
    resource_type: str | None = Field(None, description="Type of cloud resource")
    cloud_provider: str | None = Field(None, description="Cloud provider (aws, gcp, azure, snowflake)")
    connection_id: str | None = Field(None, description="Connection identifier")
    region: str | None = Field(None, description="Resource region")

    # Resource metadata and tags
    tags: dict[str, Any] = Field(default_factory=dict, description="Resource tags")
    cost_data: dict[str, Any] = Field(default_factory=dict, description="Cost information")

    # Timestamps
    created: str | None = Field(None, description="Resource creation timestamp")
    last_seen: str | None = Field(None, description="Last seen timestamp")


# NOTE: ResourceGroup, ResourceGroupsResponse, ProjectionData, and ResourceProjectionResponse
# models have been removed because the corresponding V4 API endpoints (/resources/groups
# and /resources/projection) are not documented in the official API specification and
# do not exist in the backend implementation. Only the single resource lookup endpoint
# (/resources/{organization_id}/{resource_id}) is supported in V4.


def get_resource_information(organization_id: str, resource_id: str, debug: bool = False) -> ResourceInfo:
    """
    Get information about a specific cloud resource using v4 API.

    Args:
        organization_id: CloudZero organization ID
        resource_id: Cloud resource identifier
        debug: Whether to show debug information

    Returns:
        ResourceInfo: Detailed resource information

    Raises:
        APIError: If the API request fails
        ValueError: If the resource is not found
    """
    if not organization_id or not resource_id:
        raise ValueError("Both organization_id and resource_id are required")

    if debug:
        console.print(f"[cyan]DEBUG: Fetching resource {resource_id} for org {organization_id} via V4 API[/]")

    try:
        # Make authenticated request to v4 resources endpoint
        response_data = get_authenticated(endpoint_path=f"resources/{organization_id}/{resource_id}", debug=debug)

        if debug:
            console.print(f"[cyan]DEBUG: Raw API response: {response_data}[/]")

        # Validate response with Pydantic model
        resource_info = ResourceInfo(**response_data)

        if debug:
            console.print(f"[green]DEBUG: Successfully retrieved resource {resource_id}[/]")

        return resource_info

    except APIError:
        # Re-raise API errors as-is
        raise
    except ValidationError as e:
        if debug:
            console.print(f"[red]DEBUG: Response validation failed: {e}[/]")
        raise APIError(f"Invalid response format from v4 API: {e}") from e
    except Exception as e:
        error_msg = f"Failed to get resource {resource_id}: {str(e)}"
        if debug:
            console.print(f"[red]DEBUG: Unexpected error: {error_msg}[/]")
        raise APIError(error_msg) from e


# NOTE: The functions get_resource_groups() and get_resource_projection() have been
# removed because these endpoints (/czops/v4/resources/groups and /czops/v4/resources/projection)
# are not documented in the official V4 API specification and do not exist in the backend.
#
# Only the single resource information endpoint is supported:
# - get_resource_information(organization_id, resource_id) -> ResourceInfo
#
# If you need resource grouping or projection functionality, please use the appropriate
# endpoints from other API groups or contact the backend team to confirm availability.
