"""zuzu CLI — run / init / deploy."""

import sys
import os


def main() -> None:
    args = sys.argv[1:]
    if not args:
        print("zuzu — Build personal apps in Python")
        print()
        print("Usage: zuzu <command> [args]")
        print()
        print("Commands:")
        print("  run [app.py]    Start local dev server with live preview")
        print("  init [name]     Scaffold a new app (coming soon)")
        print("  deploy          Push to zuzu.codes (coming soon)")
        sys.exit(0)

    cmd = args[0]

    if cmd == "run":
        app_file = args[1] if len(args) > 1 else "main.py"
        if not os.path.exists(app_file):
            print(f"  Error: {app_file} not found")
            sys.exit(1)

        port = 8000
        for i, arg in enumerate(args):
            if arg in ("--port", "-p") and i + 1 < len(args):
                port = int(args[i + 1])

        from zuzu.runtime.server import serve
        serve(app_file, port=port)

    elif cmd == "init":
        name = args[1] if len(args) > 1 else "my-app"
        slug = name.lower().replace(" ", "-")
        print(f"  Creating {slug}/...")
        os.makedirs(slug, exist_ok=True)

        display_name = name.replace("-", " ").title()

        with open(os.path.join(slug, "main.py"), "w") as f:
            f.write(f'''"""{display_name} — built with zuzu."""

import zuzu

items = zuzu.record("Items",
    name="",
    status=["todo", "doing", "done"],
    notes="",
)

app = zuzu.app("{display_name}", records=[items])

with zuzu.page("Dashboard"):
    zuzu.metric("Total", items.count())
    zuzu.metric("Done", items.where(items.status == "done").count())

app.run()
''')
        print(f"  Created {slug}/main.py")
        print(f"")
        print(f"  Next steps:")
        print(f"    cd {slug}")
        print(f"    zuzu run")

    elif cmd == "deploy":
        print("  zuzu deploy — push to zuzu.codes (coming soon)")
    else:
        print(f"  Unknown command: {cmd}")
        sys.exit(1)


if __name__ == "__main__":
    main()
