
import os
import shutil
from livekit.agents import function_tool, RunContext
import psutil

# ==============================
# FILE SYSTEM
# ==============================
@function_tool()
async def create_file(context: RunContext, path: str, content: str = "") -> str:
    try:
        with open(path, 'w', encoding='utf-8') as f:
            f.write(content)
        return f"File created: {path}"
    except Exception as e:
        return f"Failed to create file: {e}"

@function_tool()
async def read_file(context: RunContext, path: str) -> str:
    try:
        with open(path, 'r', encoding='utf-8') as f:
            content = f.read()
        return content[:500] + ("..." if len(content) > 500 else "")
    except Exception as e:
        return f"Failed to read file: {e}"

@function_tool()
async def delete_file(context: RunContext, path: str) -> str:
    try:
        if os.path.isfile(path):
            os.remove(path)
            return f"File deleted: {path}"
        elif os.path.isdir(path):
            shutil.rmtree(path)
            return f"Folder deleted: {path}"
        else:
            return "Path not found"
    except Exception as e:
        return f"Delete failed: {e}"

@function_tool()
async def rename_file(context: RunContext, old_path: str, new_path: str) -> str:
    try:
        os.rename(old_path, new_path)
        return f"Renamed: {old_path} -> {new_path}"
    except Exception as e:
        return f"Rename failed: {e}"

@function_tool()
async def list_directory(context: RunContext, path: str = ".") -> str:
    try:
        items = os.listdir(path)
        if len(items) > 50:
            return f"Found {len(items)} items. First 50: " + ", ".join(items[:50])
        return ", ".join(items)
    except Exception as e:
        return f"Failed to list directory: {e}"

@function_tool()
async def create_folder(context: RunContext, path: str) -> str:
    try:
        os.makedirs(path, exist_ok=True)
        return f"Folder created: {path}"
    except Exception as e:
        return f"Failed to create folder: {e}"

@function_tool()
async def disk_usage(context: RunContext, path: str = "C:\\") -> str:
    try:
        usage = psutil.disk_usage(path)
        total_gb = usage.total / (1024**3)
        free_gb = usage.free / (1024**3)
        return f"{path} - Total: {total_gb:.1f}GB | Free: {free_gb:.1f}GB ({usage.percent}% used)"
    except Exception as e:
        return f"Failed to get disk usage: {e}"
