#!/usr/bin/env python3
import sys
import os
import difflib
import re
import builtins

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

# --- 🧠 THE UNIVERSAL DYNAMIC HEALER ---
def dynamic_healer(code, error_msg, exc_type):
    fixed_code = code
    suggestion = ""

    # 1. NameError (Har tarah ki spelling mistake fix karega)
    if exc_type == NameError:
        match = re.search(r"name '(.*)' is not defined", error_msg)
        if match:
            bad_name = match.group(1)
            # Duniya bhar ke saare valid functions ki list utha lo
            valid_names = dir(builtins) + ["os", "sys", "syk", "build_web", "build_apk"]
            # AI-like similarity check (difflib)
            closest = difflib.get_close_matches(bad_name, valid_names, n=1, cutoff=0.5)
            if closest:
                fixed_code = fixed_code.replace(bad_name, closest[0])
                suggestion = f"Typo fixed: '{bad_name}' -> '{closest[0]}'"

    # 2. SyntaxError (Har tarah ke Brackets, Quotes aur Colons fix karega)
    elif exc_type == SyntaxError:
        if "unexpected EOF" in error_msg or "was never closed" in error_msg or "unterminated" in error_msg:
            # Brackets balance karo
            open_p, close_p = fixed_code.count('('), fixed_code.count(')')
            if open_p > close_p: fixed_code += ')' * (open_p - close_p)
            open_s, close_s = fixed_code.count('['), fixed_code.count(']')
            if open_s > close_s: fixed_code += ']' * (open_s - close_s)
            
            # Quotes balance karo
            if fixed_code.count("'") % 2 != 0: fixed_code += "'"
            if fixed_code.count('"') % 2 != 0: fixed_code += '"'
            suggestion = "Auto-Balanced missing brackets/quotes ')' '\"'"
            
        elif "expected ':'" in error_msg or "invalid syntax" in error_msg:
            # Loops aur conditions ke aage colon lagao
            if any(fixed_code.strip().startswith(kw) for kw in ['if ', 'for ', 'while ', 'def ', 'class ']):
                if not fixed_code.strip().endswith(':'):
                    fixed_code += ":"
                    suggestion = "Added missing colon ':' for logic block"

    return fixed_code, suggestion

def safe_execute(code):
    try:
        try:
            result = eval(code)
            if result is not None: print(result)
        except SyntaxError:
            exec(code)
    except Exception as e:
        exc_type = type(e)
        error_msg = str(e)
        print(f"\n❌ [Error Captured]: {error_msg}")
        
        # Call the Universal Healer
        fixed_code, suggestion = dynamic_healer(code, error_msg, exc_type)
        
        if fixed_code != code:
            print(f"💡 [Universal Healer]: {suggestion}")
            print(f"📝 Fixed Code: {fixed_code}")
            choice = input("❓ Execute this fix? (y/n): ").strip().lower()
            if choice == 'y':
                print("🚀 Running...\n")
                try: 
                    try: print(eval(fixed_code)) if eval(fixed_code) is not None else None
                    except SyntaxError: exec(fixed_code)
                except Exception as ex: print(f"❌ [Failed Again]: {ex}")
            else:
                print("🛑 Aborted.")
        else:
            print("❌ [Halt] Ye error logic se bahar hai, isko manual theek karna padega.")

def main():
    if len(sys.argv) == 1:
        print("Sykus v5.1.8 (Universal Dynamic 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 __name__ == "__main__": main()
