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

const projectRoot = path.resolve(__dirname, '..')
const adbPath = path.join(projectRoot, 'exe', 'adb', 'adb.exe')

const deviceIp = process.argv[2]
const devicePort = process.argv[3] || '5555'

if (!deviceIp) {
  process.stdout.write('false\n')
  process.exit(1)
}

// Connect to device
const connectCommand = `"${adbPath}" connect ${deviceIp}:${devicePort}`
const connectOutput = execSync(connectCommand, { encoding: 'utf-8' })
const connectResult = connectOutput.trim()
const connectSuccess = connectResult.includes('connected') || connectResult.includes('already connected')

if (!connectSuccess) {
  process.stdout.write('false\n')
  process.exit(1)
}

// Verify device is actually available in device list
try {
  const devicesCommand = `"${adbPath}" devices`
  const devicesOutput = execSync(devicesCommand, { encoding: 'utf-8' })
  const deviceAddress = `${deviceIp}:${devicePort}`
  const isDeviceAvailable = devicesOutput.includes(deviceAddress) && devicesOutput.includes('device')
  
  if (isDeviceAvailable) {
    process.stdout.write('success\n')
    process.exit(0)
  } else {
    process.stdout.write('false\n')
    process.exit(1)
  }
} catch (error) {
  process.stdout.write('false\n')
  process.exit(1)
}
