import os
import sys
import time
import subprocess
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

# 👇 अब हम सब कुछ अलग फाइलों से इम्पोर्ट कर रहे हैं
from .templates import (
    APP_PY_TEMPLATE, 
    APP_NSX_TEMPLATE, 
    HOME_NSX_TEMPLATE, 
    PROFILE_NSX_TEMPLATE
)

# ---------------------------------------------------------
# 🧩 VS CODE EXTENSION — SILENT INSTALL
# ---------------------------------------------------------
def setup_vscode_extension():
    print("✨ NSX Framework: VS Code एक्सटेंशन चेक किया जा रहा है...")
    try:
        # subprocess.run ज्यादा स्टेबल है
        subprocess.run(
            ["code", "--install-extension", "NeeleshSingour.neeleshsingour", "--force"],
            capture_output=True, text=True, shell=True
        )
        print("✅ VS Code Extension रेडी है!")
    except Exception:
        print("⚠️ VS Code नहीं मिला या Path सेट नहीं है।")

# ---------------------------------------------------------
# 🔥 1. HOT RELOADING LOGIC
# ---------------------------------------------------------
class ReloadHandler(FileSystemEventHandler):
    def __init__(self):
        self.process = None
        self.start_process()

    def start_process(self):
        self.process = subprocess.Popen([sys.executable, "app.py"])

    def on_modified(self, event):
        if event.src_path.endswith((".py", ".nsx", ".html", ".css", ".js")):
            print(f"\n🔄 बदलाव मिला: {os.path.basename(event.src_path)}")
            if self.process:
                self.process.terminate()
            self.start_process()

def start_app_with_reload():
    if not os.path.exists("app.py"):
        print("❌ Error: 'app.py' नहीं मिली!")
        return
    
    print("🔥 Hot Reloading चालू है... 'src/App.nsx' में बदलाव करें।")
    event_handler = ReloadHandler()
    observer = Observer()
    observer.schedule(event_handler, path='.', recursive=True)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
        if event_handler.process:
            event_handler.process.terminate()
    observer.join()

# ---------------------------------------------------------
# 🛠️ 2. MAIN CLI COMMANDS
# ---------------------------------------------------------
def main():
    if len(sys.argv) < 2:
        print("❌ Command missing! Use: nsx create <name>, nsx start, or nsx build")
        sys.exit(1)

    cmd = sys.argv[1].lower()

    if cmd == "create":
        if len(sys.argv) < 3:
            print("❌ Project name missing!")
            sys.exit(1)
        
        project_name = sys.argv[2]
        os.makedirs(f"{project_name}/src", exist_ok=True)
        
        # 📝 मल्टी-स्क्रीन फाइल्स बनाना (Templates से उठाकर)
        files_to_create = {
            "app.py": APP_PY_TEMPLATE,
            "src/App.nsx": APP_NSX_TEMPLATE,
            "src/HomeScreen.nsx": HOME_NSX_TEMPLATE,
            "src/ProfileScreen.nsx": PROFILE_NSX_TEMPLATE
        }

        for path, content in files_to_create.items():
            with open(f"{project_name}/{path}", "w", encoding="utf-8") as f:
                f.write(content)
            
        print(f"✅ Professional Multi-screen Project '{project_name}' created!")
        setup_vscode_extension()
        
        print(f"\n👉 अब ये commands चलाओ:")
        print(f"   cd {project_name}")
        print(f"   nsx start")

    elif cmd == "start":
        start_app_with_reload()

    elif cmd == "build":
        # ... तुम्हारा पुराना PyInstaller वाला कोड यहाँ रहेगा ...
        pass
        
    else:
        print(f"❌ Unknown command: '{cmd}'")

if __name__ == "__main__":
    main()