"""File operations — cross-platform."""

import os


def file_read(path):
    """Read a file's contents."""
    try:
        path = os.path.expanduser(path)
        if not os.path.exists(path):
            return {"success": False, "error": f"File not found: {path}"}
        size = os.path.getsize(path)
        if size > 1_000_000:  # 1MB limit
            return {"success": False, "error": f"File too large: {size} bytes (max 1MB)"}
        with open(path, "r", errors="replace") as f:
            content = f.read()
        return {"success": True, "content": content, "size": size}
    except Exception as e:
        return {"success": False, "error": str(e)}


def file_write(path, content):
    """Write content to a file."""
    try:
        path = os.path.expanduser(path)
        os.makedirs(os.path.dirname(path), exist_ok=True)
        with open(path, "w") as f:
            f.write(content)
        return {"success": True, "path": path, "size": len(content)}
    except Exception as e:
        return {"success": False, "error": str(e)}


def file_list(path):
    """List directory contents."""
    try:
        path = os.path.expanduser(path)
        if not os.path.isdir(path):
            return {"success": False, "error": f"Not a directory: {path}"}
        entries = []
        for name in sorted(os.listdir(path))[:200]:  # Cap at 200 entries
            full = os.path.join(path, name)
            entry = {"name": name, "is_dir": os.path.isdir(full)}
            try:
                stat = os.stat(full)
                entry["size"] = stat.st_size
            except OSError:
                pass
            entries.append(entry)
        return {"success": True, "path": path, "entries": entries}
    except Exception as e:
        return {"success": False, "error": str(e)}
