import importlib.resources as pkg_resources
import sys

# The path to your practicals folder inside the package
PRACTICALS_PATH = "pandaspypy.practicals"

def show(name: str):
    """Prints the code of a given practical file."""
    try:
        filename = f"{name}.py"
        code = pkg_resources.read_text(PRACTICALS_PATH, filename)
        print(f"--- Code for: {name} ---\n")
        print(code)
    except FileNotFoundError:
        print(f"❌ Error: Cheatsheet '{name}' not found.")
        print("Use list_all() to see available cheatsheets.")
    except Exception as e:
        print(f"Error reading resource: {e}")

def list_all():
    """Lists all available practical files."""
    print("📚 Available cheatsheets:")
    try:
        # Check if contents is available (newer python versions might act differently with namespace packages, 
        # but with __init__.py it should work)
        files = pkg_resources.contents(PRACTICALS_PATH)
        # Filter out __init__.py and other non-cheatsheet files
        cheatsheets = [f.replace(".py", "") for f in files if f.endswith(".py") and not f.startswith("__")]
        if not cheatsheets:
            print(" - No cheatsheets found.")
            return
        for name in sorted(cheatsheets):
            print(f" - {name}")
    except Exception as e:
        print(f"Error reading cheatsheets directory: {e}")

def main():
    if len(sys.argv) < 2:
        print("Usage: pandaspypy [list|show <name>]")
        return
    
    command = sys.argv[1]
    if command == "list":
        list_all()
    elif command == "show":
        if len(sys.argv) < 3:
            print("Usage: pandaspypy show <name>")
        else:
            show(sys.argv[2])
    else:
        print(f"Unknown command: {command}")
        print("Usage: pandaspypy [list|show <name>]")

if __name__ == "__main__":
    main()