"""
Reload Graphmart Tool

This tool reloads a graphmart using the AGS REST API. A reload completely
reprocesses all data layers, which is more thorough than a refresh but takes longer.

The operation is made synchronous by polling the graphmart status until completion.
"""

import asyncio
from typing import Optional

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


async def reload_graphmart(
    graphmart_uri: Optional[str] = None,
    explanation: Optional[str] = None,
    dry_run: bool = False
) -> dict:
    """
    Reload a graphmart using the AGS REST API (synchronous operation).
    
    A reload completely reprocesses all data layers, which is more thorough
    than a refresh but takes longer. Use this for complete rebuilds.
    
    Args:
        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 reload results and timing 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": "reload_graphmart",
                "message": "Dry run completed - would reload graphmart (complete reprocessing)",
                "graphmart_uri": config['GRAPHMART_URI'],
                "server": f"{config['ANZO_SERVER']}:{config['ANZO_PORT']}",
                "explanation": explanation
            }
        
        # Extract graphmart ID for API call
        graphmart_id = extract_graphmart_id(config['GRAPHMART_URI'])
        endpoint = f"/graphmarts/{graphmart_id}/reload"
        
        # Get initial status
        try:
            initial_status_code, initial_status = make_ags_request(config, f"/graphmarts/{graphmart_id}/status")
            initial_state = initial_status.get('status', 'Unknown')
        except Exception as e:
            return {
                "success": False,
                "operation": "reload_graphmart",
                "error": f"Failed to get initial status: {str(e)}",
                "graphmart_uri": config['GRAPHMART_URI']
            }
        
        # Initiate reload
        try:
            status_code, response = make_ags_request(config, endpoint, method='POST')
            
            if status_code != 200:
                return {
                    "success": False,
                    "operation": "reload_graphmart", 
                    "error": f"Reload failed with status {status_code}",
                    "response": response,
                    "graphmart_uri": config['GRAPHMART_URI']
                }
            
        except Exception as e:
            return {
                "success": False,
                "operation": "reload_graphmart",
                "error": f"Failed to initiate reload: {str(e)}",
                "graphmart_uri": config['GRAPHMART_URI']
            }
        
        # Wait for reload to complete (return to Online status)
        target_status = "http://openanzo.org/ontologies/2008/07/System#Online"
        success, final_status, final_response = wait_for_graphmart_status(
            config, target_status, poll_interval=3, max_wait_time=600  # Reload can take longer
        )
        
        if success:
            # Extract timing information from status text
            status_text = final_response.get('statusText', '')
            
            return {
                "success": True,
                "operation": "reload_graphmart",
                "message": "Graphmart reload completed successfully (all layers reprocessed)",
                "graphmart_uri": config['GRAPHMART_URI'],
                "server": f"{config['ANZO_SERVER']}:{config['ANZO_PORT']}",
                "initial_status": initial_state,
                "final_status": final_status,
                "status_details": status_text,
                "total_statements": final_response.get('totalStatements'),
                "explanation": explanation
            }
        else:
            return {
                "success": False,
                "operation": "reload_graphmart",
                "error": "Reload operation timed out or failed to complete",
                "graphmart_uri": config['GRAPHMART_URI'],
                "initial_status": initial_state,
                "final_status": final_status,
                "final_response": final_response
            }
        
    except ValueError as e:
        return {
            "success": False,
            "operation": "reload_graphmart",
            "error": f"Configuration error: {str(e)}"
        }
    except Exception as e:
        return {
            "success": False,
            "operation": "reload_graphmart", 
            "error": f"Unexpected error: {str(e)}"
        }