import os
import glob
import shutil
from pathlib import Path

class FileSystem:
    def list_directory(self, path=".", show_hidden=False):
        try:
            files = os.listdir(path)
            if not show_hidden:
                files = [f for f in files if not f.startswith(".")]
            return {"files": files}
        except Exception as e:
            return {"error": str(e)}

    def read_file(self, path, max_lines=100):
        try:
            with open(path, "r", encoding="utf-8") as f:
                lines = f.readlines()[:max_lines]
                return {"content": "".join(lines)}
        except Exception as e:
            return {"error": str(e)}

    def write_file(self, path, content):
        try:
            with open(path, "w", encoding="utf-8") as f:
                f.write(content)
            return {"success": True}
        except Exception as e:
            return {"error": str(e)}

    def create_folder(self, path):
        try:
            os.makedirs(path, exist_ok=True)
            return {"success": True}
        except Exception as e:
            return {"error": str(e)}

    def delete_file(self, path):
        try:
            os.remove(path)
            return {"success": True}
        except Exception as e:
            return {"error": str(e)}

    def delete_folder(self, path):
        try:
            os.rmdir(path)
            return {"success": True}
        except Exception as e:
            try:
                shutil.rmtree(path)
                return {"success": True, "note": "used shutil.rmtree"}
            except Exception as e2:
                return {"error": str(e2)}

    def get_file_info(self, path):
        try:
            stat = os.stat(path)
            return {
                "size": stat.st_size,
                "is_dir": os.path.isdir(path),
                "is_file": os.path.isfile(path),
                "modified": stat.st_mtime
            }
        except Exception as e:
            return {"error": str(e)}

    def get_home_directory(self):
        return {"path": str(Path.home())}

    def get_current_directory(self):
        return {"path": os.getcwd()}

    def change_directory(self, path):
        try:
            os.chdir(path)
            return {"path": os.getcwd()}
        except Exception as e:
            return {"error": str(e)}

    def search_files(self, directory, pattern):
        try:
            matches = glob.glob(os.path.join(directory, "**", pattern), recursive=True)
            return {"limit_50": matches[:50]}
        except Exception as e:
            return {"error": str(e)}
