"""
Layer Status Diagnostic Tool

This tool retrieves detailed status information for a specific layer, including
error details for all steps within the layer. This is the RECOMMENDED tool for
debugging layer and step issues, as it provides comprehensive information in
a single call.

Use this tool when:
- You see "Failed Layers" in refresh/reload responses
- A layer is not working as expected
- You need to debug all steps in a layer at once
- You want comprehensive error information

This tool provides the same step-level error details as the step status tool,
but returns information for ALL steps in the layer in one call.
"""

import asyncio
from typing import Optional

from ...utils.rest_api_utils import (
    get_ags_env_config,
    make_ags_request, 
    extract_graphmart_id
)


async def get_layer_status(
    layer_name_or_uri: str,
    graphmart_uri: Optional[str] = None,
    explanation: Optional[str] = None,
    dry_run: bool = False
) -> dict:
    """
    Get detailed status information for a layer and all its steps (RECOMMENDED).
    
    This is the primary diagnostic tool for debugging layer issues. It returns
    comprehensive information about the layer and detailed error information 
    for all steps within the layer in a single API call.
    
    Recommended over get_step_status for general debugging as it provides
    complete layer context and all step errors at once.
    
    Args:
        layer_name_or_uri: Layer name or full URI to check status for
        graphmart_uri: URI of the graphmart (optional, uses config default)
        explanation: Human-readable description of the operation
        dry_run: If true, validate inputs without executing
        
    Returns:
        JSON response with detailed layer status including:
        - Layer validation status and errors
        - Status and detailed error information for all child steps
        - Structure validity flags
        - Error stack traces with specific locations
        - Timestamps and update information
    """
    try:
        # Load connection configuration
        config = get_ags_env_config()
        
        # Override graphmart URI if provided
        if graphmart_uri:
            config['GRAPHMART_URI'] = graphmart_uri
        
        if dry_run:
            return {
                "success": True,
                "operation": "get_layer_status",
                "message": "Dry run completed - would get detailed layer status",
                "layer_name_or_uri": layer_name_or_uri,
                "graphmart_uri": config['GRAPHMART_URI'],
                "explanation": explanation,
                "note": "This tool provides comprehensive layer and step error information"
            }
        
        # Resolve layer URI if needed
        if layer_name_or_uri.startswith('http'):
            layer_uri = layer_name_or_uri
        else:
            # Need to resolve layer name to URI via AGS configuration
            # For now, assume it's a URI - in practice we'd query AGS to resolve names
            return {
                "success": False,
                "operation": "get_layer_status",
                "error": "Layer name resolution not implemented - please provide full layer URI",
                "layer_name_or_uri": layer_name_or_uri,
                "note": "Use list_transformation_layers to get layer URIs"
            }
        
        # Extract layer ID for API call
        layer_id = extract_graphmart_id(layer_uri)
        endpoint = f"/layers/{layer_id}/status?detail=true"
        
        try:
            status_code, response = make_ags_request(config, endpoint)
            
            if status_code != 200:
                return {
                    "success": False,
                    "operation": "get_layer_status",
                    "error": f"Failed to get layer status: HTTP {status_code}",
                    "layer_uri": layer_uri,
                    "response": response
                }
            
            # Extract key information for easier analysis
            layer_status = response.get('status', 'Unknown')
            is_valid = response.get('isStructureValid', False)
            child_failed = response.get('childFailed', False)
            error_count = len([child for child in response.get('child', []) 
                             if child.get('status') == 'http://openanzo.org/ontologies/2008/07/System#ValidationFailed'])
            
            return {
                "success": True,
                "operation": "get_layer_status",
                "message": f"Layer status retrieved successfully",
                "layer_uri": layer_uri,
                "layer_title": response.get('title', 'Unknown'),
                "layer_status": layer_status,
                "is_structure_valid": is_valid,
                "child_failed": child_failed,
                "total_steps": len(response.get('child', [])),
                "failed_steps": error_count,
                "graphmart_uri": config['GRAPHMART_URI'],
                "detailed_response": response,
                "explanation": explanation,
                "usage_note": "Check 'detailed_response.child' array for step-level error details"
            }
        
        except Exception as e:
            return {
                "success": False,
                "operation": "get_layer_status",
                "error": f"Failed to retrieve layer status: {str(e)}",
                "layer_uri": layer_uri,
                "graphmart_uri": config['GRAPHMART_URI']
            }
        
    except ValueError as e:
        return {
            "success": False,
            "operation": "get_layer_status",
            "error": f"Configuration error: {str(e)}"
        }
    except Exception as e:
        return {
            "success": False,
            "operation": "get_layer_status",
            "error": f"Unexpected error: {str(e)}"
        }