
import os
import logging

logger = logging.getLogger(__name__)

# Directory name for tool prompts
PROMPTS_DIR_NAME = "tool_prompts"
PROMPTS_DIR = os.path.join(os.path.dirname(__file__), PROMPTS_DIR_NAME)

def get_tool_prompt_path(filename: str) -> str:
    """Get absolute path for a tool prompt file."""
    if not filename.endswith(".txt"):
        filename += ".txt"
    return os.path.join(PROMPTS_DIR, filename)

def read_tool_prompt(filename: str, default_prompt: str = "") -> str:
    """
    Read tool prompt from file. 
    Returns default_prompt if file not found or empty.
    """
    file_path = get_tool_prompt_path(filename)
    try:
        if os.path.exists(file_path):
            with open(file_path, "r", encoding="utf-8") as f:
                content = f.read().strip()
                if content:
                    return content
    except Exception as e:
        logger.error(f"Error reading tool prompt {filename}: {e}")
    
    return default_prompt

def write_tool_prompt(filename: str, content: str) -> bool:
    """Write content to tool prompt file."""
    file_path = get_tool_prompt_path(filename)
    try:
        os.makedirs(os.path.dirname(file_path), exist_ok=True)
        with open(file_path, "w", encoding="utf-8") as f:
            f.write(content)
        return True
    except Exception as e:
        logger.error(f"Error writing tool prompt {filename}: {e}")
        return False

def list_tool_prompts() -> list[str]:
    """List all available tool prompt files."""
    try:
        if not os.path.exists(PROMPTS_DIR):
            return []
        
        files = [f for f in os.listdir(PROMPTS_DIR) if f.endswith(".txt")]
        return sorted(files)
    except Exception as e:
        logger.error(f"Error listing tool prompts: {e}")
        return []
