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

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
        if 'raw_web' in line and '"""' in line:
            ir['raw'] = content.split('"""')[1] if '"""' in content else ""
            continue
        if '=' in line and 'raw_web' not in line:
            parts = line.split('=', 1)
            ir['ui'][parts[0].strip()] = parts[1].strip().strip('"\'')
        else:
            ir['logic'].append(line)
    return ir

# --- 🛡️ 2. INTERACTIVE AUTO-HEALER (Permission Based) ---
def safe_execute(code):
    vocab = {"print": ["prnit", "pritn", "pirtn", "ptint"], "syk": ["sky", "syks"]}
    
    try:
        try:
            result = eval(code)
            if result is not None: print(result)
        except SyntaxError:
            exec(code)
    except Exception as e:
        print(f"\n❌ [Error]: {e}")
        fixed_code = code
        fixed_something = False
        
        # Galti dhundho aur fix banao
        for correct, typos in vocab.items():
            for typo in typos:
                if typo in fixed_code:
                    fixed_code = fixed_code.replace(typo, correct)
                    fixed_something = True
                    print(f"💡 [Suggestion]: Did you mean '{correct}' instead of '{typo}'?")
        
        # User se pucho
        if fixed_something:
            print(f"📝 Fixed Code: {fixed_code}")
            choice = input("❓ Do you want to execute this fixed version? (y/n): ").strip().lower()
            if choice == 'y':
                print("🚀 Running fixed code...\n")
                try: exec(fixed_code)
                except Exception as ex: print(f"❌ [Error after fix]: {ex}")
            else:
                print("🛑 Execution aborted by user. No changes made.")
        else:
            print("❌ [Safety Halt] I couldn't automatically fix this logic error. Please check your code.")

def build_web(filename):
    with open(filename, 'r') as f: ir = generate_ir(f.read())
    ui = ir['ui']
    title = ui.get('title', 'Sykus App')
    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;'><h1>{title}</h1><p>{ui.get('label', '')}</p><button style='background:#ff0055;color:white;padding:12px 24px;border:none;'>{ui.get('button', 'Click')}</button><div>{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())
    title = ir['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")

def main():
    if len(sys.argv) == 1:
        print("Sykus v5.1.6 (Interactive 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 target == "web": build_web(filename)
        elif target == "apk": build_apk(filename)

if __name__ == "__main__": main()
