"""
Caching tools for improved performance
"""

import json
import time
from typing import Dict, Any, List
from mcp.types import TextContent

from ..config import memory_cache, cache_timestamps


async def cache_results_tool(args: Dict[str, Any]) -> List[TextContent]:
    """Cache fetch results for improved performance."""
    action = args["action"]
    key = args.get("key")
    value = args.get("value")
    duration = args.get("duration", "1h")
    storage = args.get("storage", "memory")
    
    global memory_cache, cache_timestamps
    
    try:
        # Parse duration
        duration_seconds = {
            "1m": 60,
            "5m": 300,
            "15m": 900,
            "30m": 1800,
            "1h": 3600,
            "2h": 7200,
            "6h": 21600,
            "12h": 43200,
            "1d": 86400,
            "1w": 604800
        }.get(duration, 3600)
        
        current_time = time.time()
        
        if action == "get":
            if not key:
                return [TextContent(type="text", text="Key is required for 'get' action")]
            
            # Check if key exists and not expired
            if key in memory_cache and key in cache_timestamps:
                if current_time - cache_timestamps[key] < duration_seconds:
                    result = {
                        "action": "get",
                        "key": key,
                        "found": True,
                        "value": memory_cache[key],
                        "cached_at": cache_timestamps[key],
                        "expires_in": duration_seconds - (current_time - cache_timestamps[key])
                    }
                else:
                    # Expired, remove from cache
                    del memory_cache[key]
                    del cache_timestamps[key]
                    result = {
                        "action": "get",
                        "key": key,
                        "found": False,
                        "reason": "expired"
                    }
            else:
                result = {
                    "action": "get",
                    "key": key,
                    "found": False,
                    "reason": "not_found"
                }
        
        elif action == "set":
            if not key or not value:
                return [TextContent(type="text", text="Key and value are required for 'set' action")]
            
            memory_cache[key] = value
            cache_timestamps[key] = current_time
            
            result = {
                "action": "set",
                "key": key,
                "cached_at": current_time,
                "duration": duration,
                "expires_at": current_time + duration_seconds,
                "status": "cached successfully"
            }
        
        elif action == "clear":
            if key:
                # Clear specific key
                if key in memory_cache:
                    del memory_cache[key]
                if key in cache_timestamps:
                    del cache_timestamps[key]
                result = {
                    "action": "clear",
                    "key": key,
                    "status": "key cleared"
                }
            else:
                # Clear all cache
                memory_cache.clear()
                cache_timestamps.clear()
                result = {
                    "action": "clear",
                    "status": "all cache cleared"
                }
        
        elif action == "stats":
            # Clean expired entries first
            expired_keys = []
            for cache_key, timestamp in cache_timestamps.items():
                if current_time - timestamp > duration_seconds:
                    expired_keys.append(cache_key)
            
            for expired_key in expired_keys:
                if expired_key in memory_cache:
                    del memory_cache[expired_key]
                if expired_key in cache_timestamps:
                    del cache_timestamps[expired_key]
            
            result = {
                "action": "stats",
                "total_entries": len(memory_cache),
                "expired_cleaned": len(expired_keys),
                "cache_keys": list(memory_cache.keys()),
                "storage_type": storage,
                "cache_stats": {
                    "memory_entries": len(memory_cache),
                    "oldest_entry": min(cache_timestamps.values()) if cache_timestamps else None,
                    "newest_entry": max(cache_timestamps.values()) if cache_timestamps else None
                }
            }
        
        else:
            return [TextContent(type="text", text=f"Unknown action: {action}. Available: get, set, clear, stats")]
        
        return [TextContent(type="text", text=json.dumps(result, indent=2, ensure_ascii=False))]
        
    except Exception as e:
        return [TextContent(type="text", text=f"Cache operation failed: {str(e)}")]
