#!/usr/bin/env bash
# opencode-kit logging — toggle execution logging for agent behavior tracing
# Usage:
#   bash src/logging.sh enable     — turn on execution logging
#   bash src/logging.sh disable    — turn off execution logging
#   bash src/logging.sh status     — show logging state + stats
#   bash src/logging.sh export     — generate compliance report from traces

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# shellcheck source=./platform.sh
. "$SCRIPT_DIR/platform.sh"

CONTRACT_FILE=".opencode/orchestration/contract.json"
LOG_DIR=".opencode-kit/logs"
TRACE_FILE="$LOG_DIR/trace.jsonl"

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m'

resolve_contract_path() {
  local base="$SCRIPT_DIR"
  local full="$base/$CONTRACT_FILE"
  if [ -f "$full" ]; then
    echo "$full"
    return 0
  fi
  # Try from cwd as fallback
  full="$PWD/$CONTRACT_FILE"
  if [ -f "$full" ]; then
    echo "$full"
    return 0
  fi
  echo ""
  return 1
}

cmd_enable() {
  local contract
  contract="$(resolve_contract_path)" || {
    echo -e "${RED}Error: contract.json not found at $CONTRACT_FILE${NC}"
    exit 1
  }

  if [ -z "$PYTHON_CMD" ]; then
    echo -e "${RED}Error: Python required for JSON manipulation.${NC}"
    exit 1
  fi

  $PYTHON_CMD -c "
import json
path = '$contract'
with open(path) as f:
    data = json.load(f)
if 'logging' not in data:
    data['logging'] = {'enabled': False, 'output_dir': '.opencode-kit/logs', 'max_entries': 10000}
data['logging']['enabled'] = True
with open(path, 'w') as f:
    json.dump(data, f, indent=2)
print('ok')
" 2>/dev/null || {
    echo -e "${RED}Error: Failed to update contract.json${NC}"
    exit 1
  }
  echo -e "${GREEN}Execution logging enabled${NC}"
}

cmd_disable() {
  local contract
  contract="$(resolve_contract_path)" || {
    echo -e "${RED}Error: contract.json not found at $CONTRACT_FILE${NC}"
    exit 1
  }

  if [ -z "$PYTHON_CMD" ]; then
    echo -e "${RED}Error: Python required for JSON manipulation.${NC}"
    exit 1
  fi

  $PYTHON_CMD -c "
import json
path = '$contract'
with open(path) as f:
    data = json.load(f)
if 'logging' not in data:
    data['logging'] = {'enabled': False, 'output_dir': '.opencode-kit/logs', 'max_entries': 10000}
data['logging']['enabled'] = False
with open(path, 'w') as f:
    json.dump(data, f, indent=2)
print('ok')
" 2>/dev/null || {
    echo -e "${RED}Error: Failed to update contract.json${NC}"
    exit 1
  }
  echo -e "${RED}Execution logging disabled${NC}"
}

cmd_status() {
  local contract
  contract="$(resolve_contract_path)" || {
    echo -e "${RED}Error: contract.json not found at $CONTRACT_FILE${NC}"
    exit 1
  }

  if [ -z "$PYTHON_CMD" ]; then
    echo -e "${RED}Error: Python required for JSON parsing.${NC}"
    exit 1
  fi

  echo -e "${CYAN}=== Execution Logging Status ===${NC}"

  # Read enabled state
  local enabled
  enabled=$($PYTHON_CMD -c "
import json
with open('$contract') as f:
    data = json.load(f)
val = data.get('logging', {}).get('enabled', False)
print('true' if val else 'false')
")
  if [ "$enabled" = "true" ]; then
    echo -e "  State:    ${GREEN}enabled${NC}"
  else
    echo -e "  State:    ${RED}disabled${NC}"
  fi

  # Trace file stats
  local trace_dir="$SCRIPT_DIR/$LOG_DIR"
  if [ -d "$trace_dir" ] && [ -f "$trace_dir/trace.jsonl" ]; then
    local count
    count=$(wc -l < "$trace_dir/trace.jsonl" 2>/dev/null || echo 0)
    local size
    size=$(du -h "$trace_dir/trace.jsonl" 2>/dev/null | cut -f1 || echo "0")
    echo -e "  Events:   $count"
    echo -e "  Size:     $size"

    # Show last 5 entries
    echo ""
    echo -e "${CYAN}Last 5 events:${NC}"
    tail -5 "$trace_dir/trace.jsonl" 2>/dev/null | while IFS= read -r line; do
      echo "  $line"
    done
  else
    echo -e "  Events:   ${YELLOW}no traces yet${NC}"
    echo -e "  Size:     ${YELLOW}—${NC}"
  fi
}

cmd_export() {
  local trace_analysis="$SCRIPT_DIR/src/trace-analysis.sh"
  if [ -f "$trace_analysis" ]; then
    echo -e "${CYAN}Generating compliance report...${NC}"
    bash "$trace_analysis"
    echo -e "${GREEN}Report generated.${NC}"
  else
    echo -e "${YELLOW}src/trace-analysis.sh not found — no compliance report generated.${NC}"
  fi
  echo -e "  Output location: ${CYAN}.opencode-kit/logs/${NC}"
}

# --- Main dispatch ---
case "${1:-}" in
  enable)
    cmd_enable
    ;;
  disable)
    cmd_disable
    ;;
  status)
    cmd_status
    ;;
  export)
    cmd_export
    ;;
  *)
    echo "Usage: bash src/logging.sh <command>"
    echo ""
    echo "Commands:"
    echo "  enable   Turn on execution logging"
    echo "  disable  Turn off execution logging"
    echo "  status   Show logging state, event count, and file size"
    echo "  export   Generate compliance report from traces"
    exit 1
    ;;
esac
