"""
Step Status Diagnostic Tool

This tool retrieves detailed status information for a specific step.
For general debugging, use get_layer_status instead, as it provides the same
step-level information plus layer context for all steps at once.

Use this tool when:
- You know a specific step URI and want targeted debugging
- You need step-specific information for a particular step
- You're doing focused debugging on a single step

For most debugging scenarios, get_layer_status is recommended as it provides
the same step error details plus comprehensive layer context.
"""

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_step_status(
    step_name_or_uri: str,
    layer_name_or_uri: Optional[str] = None,
    graphmart_uri: Optional[str] = None,
    explanation: Optional[str] = None,
    dry_run: bool = False
) -> dict:
    """
    Get detailed status information for a specific step (use get_layer_status for general debugging).
    
    This tool provides detailed error information for a single step. For most
    debugging scenarios, get_layer_status is recommended as it provides the same
    step-level error details plus comprehensive layer context for all steps.
    
    Use this tool only when you need targeted debugging for a specific step
    and already know the step URI.
    
    Args:
        step_name_or_uri: Step name or full URI to check status for
        layer_name_or_uri: Layer context (optional, for reference)
        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 step status including:
        - Step validation status and errors
        - Error stack traces with specific locations
        - Structure validity flags
        - 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_step_status",
                "message": "Dry run completed - would get detailed step status",
                "step_name_or_uri": step_name_or_uri,
                "layer_name_or_uri": layer_name_or_uri,
                "graphmart_uri": config['GRAPHMART_URI'],
                "explanation": explanation,
                "note": "Consider using get_layer_status for comprehensive debugging"
            }
        
        # Resolve step URI if needed
        if step_name_or_uri.startswith('http'):
            step_uri = step_name_or_uri
        else:
            # Need to resolve step 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_step_status",
                "error": "Step name resolution not implemented - please provide full step URI",
                "step_name_or_uri": step_name_or_uri,
                "note": "Use list_transformation_steps to get step URIs, or use get_layer_status for comprehensive debugging"
            }
        
        # Extract step ID for API call
        step_id = extract_graphmart_id(step_uri)
        endpoint = f"/steps/{step_id}/status?detail=true"
        
        try:
            status_code, response = make_ags_request(config, endpoint)
            
            if status_code != 200:
                return {
                    "success": False,
                    "operation": "get_step_status",
                    "error": f"Failed to get step status: HTTP {status_code}",
                    "step_uri": step_uri,
                    "response": response
                }
            
            # Extract key information for easier analysis
            step_status = response.get('status', 'Unknown')
            is_valid = response.get('isStructureValid', False)
            has_error = 'error' in response
            
            return {
                "success": True,
                "operation": "get_step_status",
                "message": f"Step status retrieved successfully",
                "step_uri": step_uri,
                "step_title": response.get('title', 'Unknown'),
                "step_status": step_status,
                "is_structure_valid": is_valid,
                "has_error": has_error,
                "layer_uri": response.get('layerUri'),
                "graphmart_uri": config['GRAPHMART_URI'],
                "detailed_response": response,
                "explanation": explanation,
                "usage_note": "For comprehensive layer debugging, consider using get_layer_status instead"
            }
        
        except Exception as e:
            return {
                "success": False,
                "operation": "get_step_status",
                "error": f"Failed to retrieve step status: {str(e)}",
                "step_uri": step_uri,
                "graphmart_uri": config['GRAPHMART_URI']
            }
        
    except ValueError as e:
        return {
            "success": False,
            "operation": "get_step_status",
            "error": f"Configuration error: {str(e)}"
        }
    except Exception as e:
        return {
            "success": False,
            "operation": "get_step_status",
            "error": f"Unexpected error: {str(e)}"
        }