import logging
from pathlib import Path
from typing import Any, Dict
from PIL import Image
from tools.utils import ToolError

logger = logging.getLogger("MooseCP")

async def handle(args: Dict[str, Any]):
    """
    Extracts text-based metadata chunks (tEXt, zTXt, iTXt) from a PNG file.
    These often contain AI generation prompts and parameters.
    """
    path_str = args.get("path")
    if not path_str:
        raise ToolError("Missing path argument")
    
    path = Path(path_str)
    
    try:
        with Image.open(path) as img:
            # Metadata extraction is specific to PNG format in this implementation
            if img.format != 'PNG':
                raise ToolError("File is not a PNG image.")
            
            # Pillow parses PNG text chunks into the .info dictionary
            metadata = img.info
            if not metadata:
                return [{"type": "text", "text": "No metadata found in this PNG."}]
            
            # Format as a simple key: value list
            output = "\n".join([f"{k}: {v}" for k, v in metadata.items()])
            return [{"type": "text", "text": f"PNG Metadata:\n{output}"}]
    except ToolError:
        raise
    except Exception as e:
        raise ToolError(f"Error reading PNG metadata: {str(e)}")
