#!/usr/bin/env python3
import sys
import os

# --- 🧠 1. LEXER & IR LAYER ---
def generate_ir(content):
    ir = {"type": "app", "ui": {}, "logic": [], "raw": ""}
    lines = content.split('\n')
    for line in lines:
        line = line.strip()
        if not line or line.startswith('#'): continue
        
        # Raw Web Injection
        if 'raw_web' in line and '"""' in line:
            ir['raw'] = content.split('"""')[1] if '"""' in content else ""
            continue
            
        # UI Components (Declarative)
        if '=' in line and 'raw_web' not in line:
            parts = line.split('=', 1)
            key = parts[0].strip()
            val = parts[1].strip().strip('"\'')
            ir['ui'][key] = val
        else:
            ir['logic'].append(line)
    return ir

# --- 🛡️ 2. SAFE AUTO-HEALER (Anti-Infinite Loop) ---
def safe_execute(code, max_retries=2):
    vocab = {"print": ["prnit", "pritn", "pirtn"], "syk": ["sky", "syks"]}
    
    for attempt in range(max_retries + 1):
        try:
            try:
                result = eval(code)
                if result is not None: print(result)
            except SyntaxError:
                exec(code)
            return # Success
        except Exception as e:
            if attempt < max_retries:
                print(f"⚠️ [Auto-Healer] Error caught: {e}. Fixing AST...")
                fixed_code = code
                for correct, typos in vocab.items():
                    for typo in typos:
                        if typo in fixed_code:
                            fixed_code = fixed_code.replace(typo, correct)
                            print(f"🔧 Corrected '{typo}' -> '{correct}'")
                
                if fixed_code == code:
                    print("❌ [Safety Halt] Unfixable logic error. Aborting to prevent infinite loop.")
                    break
                code = fixed_code
            else:
                print(f"❌ [Runtime Error] Max correction limits reached: {e}")

# --- 🏭 3. MULTI-TARGET CODEGEN ---
def build_web(filename):
    with open(filename, 'r') as f: ir = generate_ir(f.read())
    ui = ir['ui']
    title = ui.get('title', 'Sykus App')
    label = ui.get('label', 'Built with Pro Engine')
    btn = ui.get('button', 'Click Here')
    
    print(f"🌐 [Sykus Web] Transpiling {filename} via IR Layer...")
    html = f"<html><head><title>{title}</title></head><body style='background:#0a0a0a;color:#00ffcc;text-align:center;padding:50px;font-family:sans-serif;'><h1>{title}</h1><p>{label}</p><button style='background:#ff0055;color:white;padding:12px 24px;border:none;border-radius:8px;font-size:16px;'>{btn}</button><div style='margin-top:30px;'>{ir['raw']}</div></body></html>"
    with open("index.html", "w") as f: f.write(html)
    print("✅ Web Build Success: index.html")

def build_apk(filename):
    with open(filename, 'r') as f: ir = generate_ir(f.read())
    ui = ir['ui']
    title = ui.get('title', 'Sykus App')
    print(f"📱 [Sykus APK] Generating scaffold for {filename}...")
    kivy = f"from kivy.app import App\nfrom kivy.uix.label import Label\nclass SykusApp(App):\n    def build(self): return Label(text='{title}')\nif __name__ == '__main__': SykusApp().run()"
    with open("sykus_app.py", "w") as f: f.write(kivy)
    print("✅ APK Scaffold Ready: sykus_app.py")

# --- 🚀 4. MAIN CLI ---
def main():
    if len(sys.argv) == 1:
        print("Sykus v5.1.5 (Pro Architecture + Safe Healer) 🔥")
        while True:
            try:
                code = input("syk <<< ")
                if code.lower() in ["exit()", "quit"]: break
                if code.strip(): safe_execute(code)
            except (EOFError, KeyboardInterrupt): break
        return

    if len(sys.argv) >= 4 and sys.argv[1] == "build":
        target, filename = sys.argv[2], sys.argv[3]
        if not os.path.exists(filename):
            print(f"❌ Error: {filename} not found.")
            return
        if target == "web": build_web(filename)
        elif target == "apk": build_apk(filename)
    else:
        print("Sykus Usage:\n  syk                -> Start REPL\n  syk build web file -> Generate Web App\n  syk build apk file -> Generate APK Source")

if __name__ == "__main__":
    main()
