# nsx/ns14engine.py
import webview
import os
import sys

def get_resource_path(relative_path):
    if hasattr(sys, '_MEIPASS'):
        return os.path.join(sys._MEIPASS, relative_path)
    return os.path.join(os.path.abspath("."), relative_path)

class BackendAPI:
    def __init__(self):
        self.window = None

    def set_window(self, window):
        self.window = window

    def navigate(self, screen_name, params=None):
        print(f"📡 Navigating to {screen_name} with params: {params}")
        # यहाँ हम compile_nsx को कॉल करेंगे जो नीचे डिफाइन है
        html = compile_nsx(f"src/{screen_name}.nsx", params)
        self.window.load_html(html)

def compile_nsx(file_path, props=None):
    full_path = get_resource_path(file_path)
    if not os.path.exists(full_path):
        return f"<h1>404: {file_path} Not Found</h1>"

    with open(full_path, "r", encoding="utf-8") as f:
        nsx_code = f.read()
    
    env = {"props": props} if props else {"props": {}}
    try:
        exec(nsx_code, env)
        if "render" in env:
            return env["render"]()
    except Exception as e:
        return f"<h1>Rendering Error: {e}</h1>"
    return "<h1>Error: render() missing!</h1>"

def run_nsx_app():
    api = BackendAPI()
    initial_html = compile_nsx('src/App.nsx')
    window = webview.create_window('NSX Professional App', html=initial_html, js_api=api, width=900, height=700, background_color='#111122')
    api.set_window(window)
    webview.start()