#!/usr/bin/env node
const { execSync } = require('child_process')
const path = require('path')

// Get adb path relative to project root
const projectRoot = path.resolve(__dirname, '../..')
const adbPath = path.join(projectRoot, 'exe', 'adb', 'adb.exe')

// Get device IP and port from command line arguments
const deviceIp = process.argv[2] || '192.168.2.5'
const devicePort = process.argv[3] || '5555'

if (!deviceIp) {
  console.error('Usage: node adb-connect.js <ip> [port]')
  console.error('Example: node adb-connect.js 192.168.2.5 5555')
  process.exit(1)
}

console.log(`Connecting to ${deviceIp}:${devicePort}...`)
console.log('========================================')

try {
  const connectCommand = `"${adbPath}" connect ${deviceIp}:${devicePort}`
  const output = execSync(connectCommand, { encoding: 'utf-8' })
  const result = output.trim()
  console.log(result)
  
  const isConnected = result.includes('connected') || result.includes('already connected')
  
  console.log('========================================')
  if (isConnected) {
    console.log('[OK] Device connected successfully')
    console.log('')
    process.exit(0)
  } else {
    console.log('[ERROR] Failed to connect to device')
    console.log('')
    process.exit(1)
  }
} catch (error) {
  console.log('========================================')
  console.log('[ERROR] Failed to connect to device')
  console.log('')
  if (error.message) {
    console.error(error.message)
  }
  process.exit(1)
}
