#!/usr/bin/env nu

# Provisioning Daemon Management Script
# Controls starting, stopping, and monitoring the provisioning-daemon-cli

const DAEMON_PORT = 9091
const DAEMON_HOST = "127.0.0.1"
const DAEMON_PID_FILE = "/tmp/provisioning-daemon-cli.pid"
const DAEMON_LOG_FILE = "data/provisioning-daemon-cli.log"
const DAEMON_BINARY = "provisioning-daemon-cli"

def get-pid [] {
  if ($DAEMON_PID_FILE | path exists) {
    open $DAEMON_PID_FILE | str trim
  } else {
    ""
  }
}

def is-running [pid: string] {
  if ($pid | is-empty) {
    return false
  }

  try {
    (ps | where pid == ($pid | into int) | length) > 0
  } catch {
    false
  }
}

def save-pid [pid: string] {
  let pid_dir = ($DAEMON_PID_FILE | path dirname)
  mkdir $pid_dir
  $pid | save -f $DAEMON_PID_FILE
}

def remove-pid [] {
  if ($DAEMON_PID_FILE | path exists) {
    rm $DAEMON_PID_FILE
  }
}

def start-cmd [] {
  let pid = (get-pid)

  if (is-running $pid) {
    print $"✗ Daemon already running (PID: $pid)"
    return
  }

  print "🚀 Starting provisioning-daemon-cli..."
  let log_dir = ($DAEMON_LOG_FILE | path dirname)
  mkdir $log_dir

  let start_result = (
    ^bash -c $"nohup $DAEMON_BINARY --nushell-path ~/.config/provisioning > $DAEMON_LOG_FILE 2>&1 & echo $!"
  )

  let daemon_pid = ($start_result | str trim)

  if ($daemon_pid | is-empty) or ($daemon_pid == "") {
    print "✗ Failed to start daemon"
    return
  }

  save-pid $daemon_pid
  sleep 1sec

  if (is-running $daemon_pid) {
    print "✓ Daemon started successfully (PID: $daemon_pid)"
    print $"  HTTP API: http://$DAEMON_HOST:$DAEMON_PORT/api/v1"
    print $"  Nushell: http://$DAEMON_HOST:$DAEMON_PORT/api/v1/execute"
    print $"  Logs: $DAEMON_LOG_FILE"
  } else {
    print "✗ Daemon failed to start"
    print $"  Check logs: $DAEMON_LOG_FILE"
    remove-pid
  }
}

def stop-cmd [] {
  let pid = (get-pid)

  if ($pid | is-empty) or not (is-running $pid) {
    print "✗ Daemon is not running"
    return
  }

  print $"Stopping daemon (PID: $pid)..."

  try {
    ^kill $pid
    sleep 500ms

    if (is-running $pid) {
      print "Force killing daemon..."
      ^kill -9 $pid
    }

    remove-pid
    print "✓ Daemon stopped"
  } catch {
    print "✗ Failed to stop daemon"
  }
}

def status-cmd [] {
  let pid = (get-pid)

  if ($pid | is-empty) or not (is-running $pid) {
    print "✗ Daemon is not running"
    return
  }

  print $"✓ Daemon is running (PID: $pid)"
  print $"  HTTP API: http://$DAEMON_HOST:$DAEMON_PORT/api/v1"
  print $"  Nushell: http://$DAEMON_HOST:$DAEMON_PORT/api/v1/execute"

  try {
    let response = (curl -s $"http://$DAEMON_HOST:$DAEMON_PORT/api/v1/health" | from json)
    print $"  Status: ($response.status)"
  } catch {
    print "  Health check failed (daemon may not be responding)"
  }
}

def logs-cmd [] {
  if not ($DAEMON_LOG_FILE | path exists) {
    print $"✗ Log file not found: $DAEMON_LOG_FILE"
    return
  }

  ^tail -n 100 $DAEMON_LOG_FILE
}

def restart-cmd [] {
  let pid = (get-pid)

  if (is-running $pid) {
    print "Stopping daemon..."
    stop-cmd
    sleep 1sec
  }

  start-cmd
}

def help-cmd [] {
  print "Provisioning Daemon CLI Management"
  print ""
  print "Usage: start-provisioning-daemon.nu <command>"
  print ""
  print "Commands:"
  print "  start      Start the daemon in background"
  print "  stop       Stop the running daemon"
  print "  status     Show daemon status"
  print "  logs       Show daemon logs (last 100 lines)"
  print "  restart    Restart the daemon"
  print "  help       Show this help message"
}

# Simple test: if first argument exists, use it as command
if ($nu.env | is-empty) {
  help-cmd
} else {
  # When called directly with no args, show help
  help-cmd
}
