File size: 9,074 Bytes
3762b57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
"""
Litehat Universal Engine โ€” Main Entry Point
Summon the Wizard. Manifest your dream.

Usage:
    python -m litehat summon --dream "build me a social network for gardeners"
    python -m litehat manifest --dream "create a real-time multiplayer game"
    python -m litehat heal --app my-app
    python -m litehat deploy --app my-app --env production
"""

import sys
import asyncio
import argparse

from .wizard import WizardGrimoire
from .mcp_terminal import MCPTerminal
from .kuberns_bridge import KubernsBridge, DeploymentConfig
from .self_healing import SelfHealingEngine, ContinuousMonitor


BANNER = """
โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•—
โ•‘                                                              โ•‘
โ•‘   ๐Ÿง™โ€โ™‚๏ธ  LITEHAT โ€” The Sovereign Universal Maker              โ•‘
โ•‘                                                              โ•‘
โ•‘   "I don't just write code. I launch reality."               โ•‘
โ•‘                                                              โ•‘
โ•‘   โšก Holographic Brain  |  ๐Ÿ”ฎ Wizard Interface               โ•‘
โ•‘   ๐Ÿ–ฅ๏ธ  MCP Terminal     |  โ˜๏ธ  Kuberns Deployer              โ•‘
โ•‘   ๐Ÿ’Š Self-Healing      |  ๐Ÿ“œ Eternal Chronicle               โ•‘
โ•‘                                                              โ•‘
โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
"""


def create_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        description="๐Ÿง™โ€โ™‚๏ธ Litehat โ€” The Sovereign Universal Maker",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  python -m litehat summon --dream "build me a todo app with AI features"
  python -m litehat deploy --app my-app --domain myapp.litehat.app
  python -m litehat heal --app my-app
  python -m litehat monitor --apps my-app,other-app
        """,
    )

    subparsers = parser.add_subparsers(dest="command", help="Commands")

    # Summon: Start a new project
    summon_parser = subparsers.add_parser("summon", help="Summon the Wizard with a dream")
    summon_parser.add_argument("--dream", "-d", type=str, required=True,
                               help="Your dream โ€” what to build")
    summon_parser.add_argument("--project", "-p", type=str, default=".",
                               help="Project directory")
    summon_parser.add_argument("--stack", "-s", type=str, default="auto",
                               help="Tech stack (auto-detected if not specified)")

    # Manifest: Full build + deploy pipeline
    manifest_parser = subparsers.add_parser("manifest", help="Manifest a dream end-to-end")
    manifest_parser.add_argument("--dream", "-d", type=str, required=True,
                                 help="Your dream")
    manifest_parser.add_argument("--deploy", action="store_true", default=True,
                                 help="Deploy after building (default: true)")
    manifest_parser.add_argument("--domain", type=str, default=None,
                                 help="Custom domain for deployment")

    # Deploy: Deploy an existing project
    deploy_parser = subparsers.add_parser("deploy", help="Deploy an application")
    deploy_parser.add_argument("--app", "-a", type=str, required=True,
                               help="Application name")
    deploy_parser.add_argument("--domain", type=str, default=None,
                               help="Custom domain")
    deploy_parser.add_argument("--port", type=int, default=3000,
                               help="Application port")
    deploy_parser.add_argument("--env", type=str, default="production",
                               help="Environment (production/staging)")

    # Heal: Self-healing for a deployed app
    heal_parser = subparsers.add_parser("heal", help="Self-heal an application")
    heal_parser.add_argument("--app", "-a", type=str, required=True,
                             help="Application name")

    # Monitor: Continuous monitoring
    monitor_parser = subparsers.add_parser("monitor", help="Continuous monitoring")
    monitor_parser.add_argument("--apps", type=str, required=True,
                                help="Comma-separated app names to monitor")

    # Terminal: Direct MCP terminal access
    terminal_parser = subparsers.add_parser("terminal", help="Open MCP terminal")
    terminal_parser.add_argument("--command", "-c", type=str, default=None,
                                 help="Execute a command directly")

    # Init: Initialize a new Litehat project
    init_parser = subparsers.add_parser("init", help="Initialize a Litehat project")
    init_parser.add_argument("--name", "-n", type=str, required=True,
                             help="Project name")

    return parser


async def handle_summon(args):
    """Handle the summon command."""
    print(BANNER)
    wizard = WizardGrimoire()
    report = await wizard.manifest_dream(args.dream)
    return report


async def handle_manifest(args):
    """Handle the manifest command โ€” full build + deploy pipeline."""
    print(BANNER)
    wizard = WizardGrimoire()

    if args.domain:
        wizard.domain = args.domain

    report = await wizard.manifest_dream(args.dream)
    return report


def handle_deploy(args):
    """Handle the deploy command."""
    bridge = KubernsBridge()

    config = DeploymentConfig(
        app_name=args.app,
        image=f"{args.app}:latest",
        port=args.port,
        domain=args.domain,
    )

    status = bridge.deploy(config)

    if status.deployed:
        print(f"\nโœ… {args.app} is live at: {status.url}")
    else:
        print(f"\nโŒ Deployment failed: {status.last_error}")
        # Auto-heal
        print("๐Ÿ’Š Initiating self-healing...")
        healer = SelfHealingEngine()
        event = healer.detect_failure(args.app, status.last_error or "", 503)
        if event:
            healer.heal(event)

    return status


def handle_heal(args):
    """Handle the heal command."""
    healer = SelfHealingEngine()
    health_report = healer.get_health_report()

    print(f"๐Ÿ’Š Self-Healing Report for {args.app}")
    print(f"   Total failures: {health_report['total_failures']}")
    print(f"   Healed: {health_report['healed']}")
    print(f"   Heal rate: {health_report['heal_rate']:.0%}")

    return health_report


async def handle_monitor(args):
    """Handle the monitor command."""
    app_names = [a.strip() for a in args.apps.split(",")]

    healer = SelfHealingEngine()
    monitor = ContinuousMonitor(healer)

    for app in app_names:
        monitor.register_app(app, f"https://{app}.litehat.app/health")
        print(f"๐Ÿ‘๏ธ  Monitoring {app}...")

    print("๐Ÿง™โ€โ™‚๏ธ The Wizard watches over your apps...")
    await monitor.monitor_loop()


def handle_terminal(args):
    """Handle the terminal command."""
    terminal = MCPTerminal()

    if args.command:
        result = terminal.execute(args.command)
        print(f"$ {args.command}")
        if result.stdout:
            print(result.stdout)
        if result.stderr:
            print(f"ERROR: {result.stderr}")
        print(f"Exit: {result.exit_code} | Time: {result.elapsed_ms:.0f}ms")
    else:
        print("MCP Terminal ready. Use --command to execute.")
        print(f"Workspace: {terminal.workspace_root}")


def handle_init(args):
    """Handle the init command."""
    terminal = MCPTerminal()

    print(f"๐Ÿ”ฎ Initializing Litehat project: {args.name}")

    # Create project structure
    terminal.write_file(f"{args.name}/README.md", f"# {args.name}\n\nBuilt with Litehat ๐Ÿง™โ€โ™‚๏ธ\n")
    terminal.write_file(f"{args.name}/.litehat/config.json",
                        '{"version": "1.0", "created_by": "Litehat Universal Engine"}')
    terminal.write_file(f"{args.name}/.github/workflows/deploy.yml",
                        f"# Auto-generated by Litehat\n# CI/CD for {args.name}\n")

    print(f"โœ… Project {args.name} initialized!")
    print(f"   Run: cd {args.name} && python -m litehat summon --dream 'your dream'")


async def main():
    """Main entry point."""
    parser = create_parser()
    args = parser.parse_args()

    if not args.command:
        parser.print_help()
        print("\n๐Ÿง™โ€โ™‚๏ธ The Wizard awaits your command...")
        return 1

    handlers = {
        "summon": handle_summon,
        "manifest": handle_manifest,
        "deploy": handle_deploy,
        "heal": handle_heal,
        "monitor": handle_monitor,
        "terminal": handle_terminal,
        "init": handle_init,
    }

    handler = handlers.get(args.command)
    if handler:
        if asyncio.iscoroutinefunction(handler):
            await handler(args)
        else:
            handler(args)

    return 0


if __name__ == "__main__":
    sys.exit(asyncio.run(main()))