#!/usr/bin/env bash
# commands/activity/show.sh

function cmd::activity::show::on_load() {
  command::mixin json_output [section="Output"]

  help::section "Filters"
  flag::define --peer             value "Filter by peer name"      label:name                 section:Filters
  flag::define --type             value "Filter by device type"    label:type                 section:Filters
  flag::define --service          value "Filter by service"        label:service              section:Filters
  flag::define --ip               value "Filter by destination IP" label:ip                   section:Filters
  flag::define --hours            value "Hours to look back"       default:24 type:int min:0  section:Filters
  flag::define --exclude-service[] "Exclude service from output"   label:service              section:Filters
  flag::define --include-service[] "Override excluded service"     label:service              section:Filters

  help::section "Display"
  flag::define --accept   bool "Show only accepted traffic"   section:Display
  flag::define --drop     bool "Show only firewall drops"     section:Display
  flag::define --external bool "Show only external traffic"   section:Display
  flag::define --ports    bool "Show raw IP:port annotations" section:Display

  flag::exclusive --accept --drop
}

function cmd::activity::show::run() {
  flag::parse "$@" || return 1

  local filter_peer;    filter_peer=$(flag::value --peer)
  local filter_service; filter_service=$(flag::value --service)
  local filter_ip;      filter_ip=$(flag::value --ip)
  local filter_type;    filter_type=$(flag::value --type)
  local hours;          hours=$(flag::value --hours)
  local accept_only=false drop_only=false external_only=false show_ports=false

  flag::bool --accept   && accept_only=true
  flag::bool --drop     && drop_only=true
  flag::bool --external && external_only=true
  flag::bool --ports    && show_ports=true

  # Build exclusion list — remove any --include-service entries
  local -a exclude_services=() include_services=()
  while IFS= read -r svc; do
    [[ -n "$svc" ]] && exclude_services+=("$svc")
  done < <(flag::array --exclude-service)
  while IFS= read -r svc; do
    [[ -n "$svc" ]] && include_services+=("$svc")
  done < <(flag::array --include-service)

  local -a final_excludes=()
  for svc in "${exclude_services[@]:-}"; do
    local included=false
    for inc in "${include_services[@]:-}"; do
      [[ "$svc" == "$inc" ]] && included=true && break
    done
    $included || final_excludes+=("$svc")
  done

  local exclude_str=""
  [[ ${#final_excludes[@]} -gt 0 ]] && \
    exclude_str=$(IFS=' '; echo "${final_excludes[*]}")

  if command::json; then
    cmd::activity::_output_json "$hours"
    return 0
  fi

  cmd::activity::_impl \
    "$filter_peer" "$filter_service" "$filter_ip" "$filter_type" \
    "$hours" "$accept_only" "$drop_only" "$external_only" \
    "$show_ports" "$exclude_str"
}