# Copyright [2025] [IBM]
# Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
# See the LICENSE file in the project root for license information.

from typing import Optional

from app.core.registry import service_registry
from app.shared.logging import LOGGER, auto_context
from app.shared.utils.tool_helper_service import tool_helper_service
from app.services.catalog.models.list_schemas import (
    ListSchemasRequest,
    ListSchemasResponse,
)


@service_registry.tool(
    name="list_schemas",
    description="""
    List all schemas in a catalog using IBM watsonx.data lakehouse API.
    
    This tool retrieves all schema names available in a specified catalog using a given engine.
    
    IMPORTANT CONSTRAINTS:
    - catalog_id: Must be 1-128 characters, alphanumeric with hyphens/underscores only
    - engine_id: Must be 1-128 characters, alphanumeric with hyphens only
    - auth_instance_id: Must be a valid CRN (Cloud Resource Name), 1-128 characters
    
    Returns:
        ListSchemasResponse: Contains message, message_code, and list of schema names
    
    Example:
        catalog_id: "my_catalog"
        engine_id: "presto-01"
        auth_instance_id: "crn:v1:bluemix:public:lakehouse:us-south:a/..."
    """,
    tags={"catalog", "schema", "lakehouse"},
    meta={"version": "1.0", "service": "catalog"},
)
@auto_context
async def list_schemas(
    request: ListSchemasRequest,
) -> ListSchemasResponse:
    """
    List all schemas in a catalog.
    
    Args:
        request: ListSchemasRequest containing catalog_id, engine_id, and auth_instance_id
        
    Returns:
        ListSchemasResponse with list of schema names
    """
    LOGGER.info(
        "Calling tool 'list_schemas' for catalog %s with engine %s",
        request.catalog_id,
        request.engine_id,
    )

    # Construct the URL based on the API specification
    # The lakehouse API uses a different URL pattern than the standard DI service
    # Extract region from base_url if it contains lakehouse, otherwise construct it
    base_url_str = str(tool_helper_service.base_url)
    
    # Check if base_url already contains lakehouse endpoint
    if "lakehouse.cloud.ibm.com" in base_url_str:
        # Use the base URL as-is
        lakehouse_base = base_url_str.rstrip('/')
    else:
        # Extract region from the service URL (e.g., us-south from api.dataplatform.cloud.ibm.com)
        # For now, construct the lakehouse URL by replacing the domain
        # This assumes the service URL follows the pattern: https://api.{service}.{region}.cloud.ibm.com
        if ".cloud.ibm.com" in base_url_str:
            # Extract the region part (e.g., us-south, eu-de)
            # For SaaS: https://api.dataplatform.cloud.ibm.com -> https://us-south.lakehouse.cloud.ibm.com
            # Default to us-south if region cannot be determined
            lakehouse_base = base_url_str.replace("api.dataplatform", "us-south.lakehouse")
        else:
            # For CPD or other environments, use the base URL directly
            lakehouse_base = base_url_str.rstrip('/')
    
    url = f"{lakehouse_base}/lakehouse/api/v2/catalogs/{request.catalog_id}/schemas"
    
    # Set up query parameters
    params = {
        "engine_id": request.engine_id
    }
    
    # Set up headers with AuthInstanceId
    headers = {
        "accept": "application/json",
        "AuthInstanceId": request.auth_instance_id
    }

    # Execute the GET request
    response = await tool_helper_service.execute_get_request(
        url=url,
        params=params,
        headers=headers,
        tool_name="list_schemas"
    )

    # Extract response data
    response_data = response.get("response", {})
    message = response_data.get("message", "list all schemas")
    message_code = response_data.get("message_code", "success")
    schemas = response.get("schemas", [])

    LOGGER.info(
        "Successfully retrieved %d schemas from catalog %s",
        len(schemas),
        request.catalog_id
    )

    return ListSchemasResponse(
        message=message,
        message_code=message_code,
        schemas=schemas
    )


@service_registry.tool(
    name="list_schemas",
    description="""
    List all schemas in a catalog using IBM watsonx.data lakehouse API.
    
    This tool retrieves all schema names available in a specified catalog using a given engine.
    
    IMPORTANT CONSTRAINTS:
    - catalog_id: Must be 1-128 characters, alphanumeric with hyphens/underscores only
    - engine_id: Must be 1-128 characters, alphanumeric with hyphens only
    - auth_instance_id: Must be a valid CRN (Cloud Resource Name), 1-128 characters
    
    Returns:
        ListSchemasResponse: Contains message, message_code, and list of schema names
    
    Example:
        catalog_id: "my_catalog"
        engine_id: "presto-01"
        auth_instance_id: "crn:v1:bluemix:public:lakehouse:us-south:a/..."
    """,
    tags={"catalog", "schema", "lakehouse", "wxo"},
    meta={"version": "1.0", "service": "catalog"},
)
@auto_context
async def wxo_list_schemas(
    catalog_id: str,
    engine_id: str,
    auth_instance_id: str,
) -> ListSchemasResponse:
    """
    Watsonx Orchestrator compatible wrapper for list_schemas.
    
    Args:
        catalog_id: Catalog name/ID to list schemas from
        engine_id: Engine name/ID to use for listing schemas
        auth_instance_id: CRN (Cloud Resource Name) for authorization
        
    Returns:
        ListSchemasResponse with list of schema names
    """
    request = ListSchemasRequest(
        catalog_id=catalog_id,
        engine_id=engine_id,
        auth_instance_id=auth_instance_id,
    )
    
    return await list_schemas(request)

# Made with Bob
