#!/usr/bin/env python3
"""Test npm install directly."""

import subprocess
from pathlib import Path
import sys
import os

install_base = Path.home() / ".local" / "openclaw-installer"
node_dir = install_base / "node"
npm_path = node_dir / "npm.cmd" if sys.platform == "win32" else node_dir / "npm"
openclaw_dir = install_base / "openclaw"
openclaw_dir.mkdir(parents=True, exist_ok=True)

print(f"npm path: {npm_path}")
print(f"npm exists: {npm_path.exists()}")
print(f"openclaw dir: {openclaw_dir}")
print(f"Running npm install openclaw@latest in: {openclaw_dir}")
print()

# Set up environment
env = os.environ.copy()
env["PATH"] = str(node_dir) + os.pathsep + env.get("PATH", "")

# Run npm install
cmd = [str(npm_path), "install", "openclaw@latest"]
print(f"Command: {' '.join(cmd)}")
print()

result = subprocess.run(
    cmd,
    cwd=str(openclaw_dir),
    capture_output=True,
    text=True,
    env=env,
)

print(f"Return code: {result.returncode}")
print(f"STDOUT:\n{result.stdout}")
print(f"STDERR:\n{result.stderr}")
print()

# Check if openclaw was installed
target_dir = openclaw_dir / "node_modules" / "openclaw"
print(f"Checking for openclaw at: {target_dir}")
print(f"Exists: {target_dir.exists()}")
if target_dir.exists():
    print("✓ OpenClaw installed successfully!")
    if (target_dir / "openclaw.mjs").exists():
        print("✓ openclaw.mjs found")
else:
    print("✗ OpenClaw not found")
