#!/usr/bin/env python3
"""
Figma DSL MCP - Python wrapper for TypeScript MCP server
"""
import os
import sys
import subprocess
import shutil
from pathlib import Path

def find_nodejs():
    """Find Node.js executable"""
    node_exe = shutil.which('node')
    if node_exe:
        return node_exe
    
    # Try common Node.js installation paths
    possible_paths = []
    
    if sys.platform == "win32":
        possible_paths = [
            r"C:\Program Files\nodejs\node.exe",
            r"C:\Program Files (x86)\nodejs\node.exe",
            os.path.expanduser(r"~\AppData\Roaming\npm\node.exe")
        ]
    elif sys.platform == "darwin":  # macOS
        possible_paths = [
            "/usr/local/bin/node",
            "/opt/homebrew/bin/node",
            "/usr/bin/node"
        ]
    else:  # Linux
        possible_paths = [
            "/usr/bin/node",
            "/usr/local/bin/node",
            "/snap/bin/node"
        ]
    
    for path in possible_paths:
        if os.path.exists(path):
            return path
    
    return None

def get_typescript_project_root():
    """Get the path to the TypeScript project root"""
    # This file is in python-package/src/dsl_mcp/cli.py
    # TypeScript project is in the parent of python-package
    current_file = Path(__file__).resolve()
    python_package_dir = current_file.parent.parent.parent  # python-package
    ts_project_root = python_package_dir.parent  # Figma-Context-MCP-main
    
    return ts_project_root

def ensure_dependencies_installed(ts_project_root):
    """Ensure TypeScript dependencies are installed"""
    node_modules = ts_project_root / "node_modules"
    package_json = ts_project_root / "package.json"
    
    if not package_json.exists():
        print(f"Error: package.json not found at {package_json}", file=sys.stderr)
        return False
    
    if not node_modules.exists():
        print("Installing TypeScript dependencies...")
        try:
            # Try npm first
            result = subprocess.run(
                ["npm", "install"],
                cwd=ts_project_root,
                capture_output=True,
                text=True
            )
            if result.returncode != 0:
                print(f"npm install failed: {result.stderr}", file=sys.stderr)
                return False
            print("Dependencies installed successfully")
        except Exception as e:
            print(f"Failed to install dependencies: {e}", file=sys.stderr)
            return False
    
    return True

def ensure_project_built(ts_project_root):
    """Ensure TypeScript project is built"""
    dist_dir = ts_project_root / "dist"
    bin_js = dist_dir / "bin.js"
    
    if not bin_js.exists():
        print("Building TypeScript project...")
        try:
            result = subprocess.run(
                ["npm", "run", "build"],
                cwd=ts_project_root,
                capture_output=True,
                text=True
            )
            if result.returncode != 0:
                print(f"Build failed: {result.stderr}", file=sys.stderr)
                return False
            print("Build completed successfully")
        except Exception as e:
            print(f"Failed to build project: {e}", file=sys.stderr)
            return False
    
    return True

def main():
    """Main entry point for the Python wrapper"""
    # Find Node.js
    node_exe = find_nodejs()
    if not node_exe:
        print("Error: Node.js not found. Please install Node.js from https://nodejs.org/", file=sys.stderr)
        sys.exit(1)
    
    # Get TypeScript project root
    ts_project_root = get_typescript_project_root()
    if not ts_project_root.exists():
        print(f"Error: TypeScript project not found at {ts_project_root}", file=sys.stderr)
        sys.exit(1)
    
    # Ensure dependencies are installed
    if not ensure_dependencies_installed(ts_project_root):
        sys.exit(1)
    
    # Ensure project is built
    if not ensure_project_built(ts_project_root):
        sys.exit(1)
    
    # Run the MCP server
    bin_js = ts_project_root / "dist" / "bin.js"
    if not bin_js.exists():
        print(f"Error: Built file not found at {bin_js}", file=sys.stderr)
        sys.exit(1)
    
    # Pass all arguments to the Node.js application
    args = [node_exe, str(bin_js)] + sys.argv[1:]
    
    try:
        sys.exit(subprocess.run(args, cwd=ts_project_root).returncode)
    except KeyboardInterrupt:
        sys.exit(0)
    except Exception as e:
        print(f"Error running MCP server: {e}", file=sys.stderr)
        sys.exit(1)

if __name__ == "__main__":
    main()