import { execFile } from 'child_process'
import { networkInterfaces } from 'os'

/**
 * Detect the Tailscale IPv4 address. Tries the CLI first,
 * falls back to scanning network interfaces for 100.x.x.x.
 */
export async function getTailscaleIP(): Promise<string | null> {
  // Try tailscale CLI
  const cliIP = await tryTailscaleCLI()
  if (cliIP) return cliIP

  // Fallback: scan network interfaces for Tailscale CGNAT range (100.64-127.x.x)
  const ifaces = networkInterfaces()
  for (const addrs of Object.values(ifaces)) {
    if (!addrs) continue
    for (const addr of addrs) {
      if (addr.family === 'IPv4' && addr.address.startsWith('100.')) {
        const second = parseInt(addr.address.split('.')[1]!, 10)
        if (second >= 64 && second <= 127) return addr.address
      }
    }
  }

  return null
}

function tryTailscaleCLI(): Promise<string | null> {
  return new Promise((resolve) => {
    // Try common paths
    const paths = [
      'tailscale',
      '/usr/bin/tailscale',
      '/usr/local/bin/tailscale',
      'C:\\Program Files\\Tailscale\\tailscale.exe',
    ]

    let tried = 0
    for (const bin of paths) {
      execFile(bin, ['ip', '-4'], { timeout: 3000 }, (err, stdout) => {
        tried++
        if (!err && stdout.trim()) {
          resolve(stdout.trim().split('\n')[0]!)
          return
        }
        if (tried === paths.length) resolve(null)
      })
    }
  })
}
