#!/usr/bin/env bash
set -euo pipefail

# 注意: 进程互斥检查由Python代码通过文件锁实现，无需在Shell脚本中检查

# 检测语言环境（根据LANG环境变量）
detect_language() {
  local lang="${LANG:-}"
  if [[ "$lang" =~ ^zh ]]; then
    echo "zh_CN"
  else
    echo "en_US"
  fi
}

print_help() {
  python3 -c "
import sys
sys.path.insert(0, '$(dirname "$(readlink -f "$0")")/../..')
from ks_prov_shared.i18n import t, set_language
set_language('$(detect_language)')
help_text = f'''{t('Configuration Comparison Tool ks-prov-compare')}

{t('Description')}:
  {t('Compare differences between two configuration databases and generate detailed difference reports, including')}:
  - {t('File configuration differences')}
  - {t('Command execution result differences')}
  - {t('Service status differences')}
  - {t('Software package version differences')}

{t('Usage')}:
  ks-prov-compare                    # {t('Enter interactive wizard mode')}
  ks-prov-compare -h|--help          # {t('Show this help message')}

{t('Interactive Parameters')}:
  1) {t('Baseline database path')}
     {t('Specify the baseline configuration database file (SQLite format)')}
     {t('Default')}: baseline.db
     {t('Tip')}: {t('If you input a directory path, baseline.db will be automatically appended')}

  2) {t('Current database path')}
     {t('Specify the current configuration database file (SQLite format)')}
     {t('Default')}: current.db
     {t('Tip')}: {t('If you input a directory path, current.db will be automatically appended')}

  3) {t('Output path or directory')}
     {t('Specify the output path or directory for the difference report (CSV format)')}
     {t('Default')}: diff.csv
     {t('Tip')}: {t('If you input a directory path, diff.csv will be automatically appended')}

{t('Output File Description (CSV Format)')}:
  {t('All CSV filenames and output directory names will automatically include timestamps')}
  (Format: 2512-311402, representing December 31, 2025 at 14:02)
  - {t('If output is a file path, filename format: {format}', format='{prefix}_{category}_{timestamp}.csv')}
    Example: diff_config_files_2512-311402.csv
  - {t('If output is a directory, directory format: {dir_format}, file format: {file_format}', dir_format='{dirname}_{timestamp}', file_format='diff_{category}_{timestamp}.csv')}
    Example: result_2512-311402/diff_config_files_2512-311402.csv
  - diff_config_files.csv      {t('Configuration file differences')}
  - diff_command_results.csv   {t('Command execution result differences')}
  - diff_services.csv          {t('Service status differences')}
  - diff_packages.csv          {t('Software package differences')}

{t('Command Line Mode (Advanced Usage)')}:
  python -m ks_prov_compare.compare_cli compare \\
    --baseline <baseline_database_path> \\
    --current <current_database_path> \\
    --output <output_path_or_directory>

{t('Parameters')}:
  --baseline BASELINE   {t('Baseline database file path (required)')}
  --current CURRENT     {t('Current database file path (required)')}
  --output OUTPUT       {t('Report output path or directory (CSV format)')}

{t('Examples')}:
  # {t('Compare two databases and generate CSV report')}
  ks-prov-compare
  # {t('Interactive input')}:
  # 1) /opt/baseline.db
  # 2) /opt/current.db
  # 3) /opt/reports/
'''
print(help_text)
" 2>/dev/null || cat <<'EOF'
ks-prov-compare - Configuration Comparison Tool

Description:
  Compare differences between two configuration databases and generate detailed difference reports, including:
  - File configuration differences
  - Command execution result differences
  - Service status differences
  - Software package version differences

Usage:
  ks-prov-compare                    # Enter interactive wizard mode
  ks-prov-compare -h|--help          # Show this help message

Interactive Parameters:
  1) Baseline database path
     Specify the baseline configuration database file (SQLite format)
     Default: baseline.db
     Tip: If you input a directory path, baseline.db will be automatically appended

  2) Current database path
     Specify the current configuration database file (SQLite format)
     Default: current.db
     Tip: If you input a directory path, current.db will be automatically appended

  3) Output path or directory
     Specify the output path or directory for the difference report (CSV format)
     Default: diff.csv
     Tip: If you input a directory path, diff.csv will be automatically appended

Output File Description (CSV Format):
  All CSV filenames and output directory names will automatically include timestamps
  (Format: 2512-311402, representing December 31, 2025 at 14:02)
  - If output is a file path, filename format: {prefix}_{category}_{timestamp}.csv
    Example: diff_config_files_2512-311402.csv
  - If output is a directory, directory format: {dirname}_{timestamp}, file format: diff_{category}_{timestamp}.csv
    Example: result_2512-311402/diff_config_files_2512-311402.csv
  - diff_config_files.csv      Configuration file differences
  - diff_command_results.csv   Command execution result differences
  - diff_services.csv          Service status differences
  - diff_packages.csv          Software package differences

Command Line Mode (Advanced Usage):
  python -m ks_prov_compare.compare_cli compare \
    --baseline <baseline_database_path> \
    --current <current_database_path> \
    --output <output_path_or_directory>

Parameters:
  --baseline BASELINE   Baseline database file path (required)
  --current CURRENT     Current database file path (required)
  --output OUTPUT       Report output path or directory (CSV format)

Examples:
  # Compare two databases and generate CSV report
  ks-prov-compare
  # Interactive input:
  # 1) /opt/baseline.db
  # 2) /opt/current.db
  # 3) /opt/reports/
EOF
}

if [[ ${1:-} == "-h" || ${1:-} == "--help" ]]; then
  print_help
  exit 0
fi

CONFIG_FILE="/etc/ks-prov.conf"
DEFAULT_DIR="/opt/ks-prov-dir"
DEFAULT_RESULT_DIR="${DEFAULT_DIR}/result"
if [[ -f "$CONFIG_FILE" ]]; then
  # shellcheck disable=SC1090
  source "$CONFIG_FILE"
fi
mkdir -p "$DEFAULT_DIR" "$DEFAULT_RESULT_DIR"

# 获取翻译后的文本（通过Python翻译模块）
get_text() {
  local key="$1"
  shift
  # 调用Python翻译模块获取文本
  python3 -c "
import sys
sys.path.insert(0, '$(dirname "$(readlink -f "$0")")/../..')
from ks_prov_shared.i18n import t, set_language
set_language('$(detect_language)')
print(t('$key'$(printf ", %s='%s'" "$@" 2>/dev/null || true)))
" 2>/dev/null || echo "$key"
}

# 根据语言环境设置提示文本
LANG_CODE=$(detect_language)
if [[ "$LANG_CODE" == "zh_CN" ]]; then
  # 中文提示
  MSG_WIZARD="=== ks-prov-compare 交互式向导 ==="
  MSG_TIP="提示: 输入 q 或 quit 可随时退出"
  MSG_EXIT="已退出"
  MSG_BASELINE_PROMPT="1) 基线数据库路径 (回车使用默认路径): "
  MSG_CURRENT_PROMPT="2) 当前数据库路径"
  MSG_OUTPUT_PROMPT="3) 结果输出基准(可为目录或文件前缀)"
  MSG_ERROR_BASELINE_NOT_FOUND="错误: 基线数据库文件不存在，请安装对应版本基线数据库"
  MSG_ERROR_CURRENT_NOT_FOUND="错误: 当前数据库文件不存在"
  MSG_EXECUTING=">> 即将执行:"
else
  # 英文提示
  MSG_WIZARD="=== ks-prov-compare Interactive Wizard ==="
  MSG_TIP="Tip: Type 'q' or 'quit' to exit at any time"
  MSG_EXIT="Exited"
  MSG_BASELINE_PROMPT="1) Baseline database path (Press Enter for default): "
  MSG_CURRENT_PROMPT="2) Current database path"
  MSG_OUTPUT_PROMPT="3) Output path (directory or file prefix)"
  MSG_ERROR_BASELINE_NOT_FOUND="Error: Baseline database file not found, please install the corresponding version baseline database"
  MSG_ERROR_CURRENT_NOT_FOUND="Error: Current database file not found"
  MSG_EXECUTING=">> About to execute:"
fi

echo "$MSG_WIZARD"
echo "$MSG_TIP"
echo ""

# 检查退出命令的辅助函数
check_exit() {
  local input="$1"
  # 只有在输入不为空时才检查退出命令
  if [[ -n "$input" ]] && [[ "${input,,}" == "q" || "${input,,}" == "quit" ]]; then
    echo "$MSG_EXIT"
    exit 0
  fi
}

# 清理输入：去除前后空格和控制字符（包括Tab）
clean_input() {
  local input="$1"
  # 去除前后空格
  input=$(echo "$input" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
  # 去除控制字符（包括Tab、回车等）
  input=$(echo "$input" | tr -d '\000-\037')
  echo "$input"
}

# 默认数据库与结果路径
DEFAULT_BASELINE_DB="/usr/share/ks-prov/baseline.db"
DEFAULT_CURRENT_DB="/opt/ks-prov-dir/current.db"
DEFAULT_REPORT_DIR="/opt/ks-prov-dir/result"

read -erp "$MSG_BASELINE_PROMPT" BASELINE_DB
BASELINE_DB=$(clean_input "$BASELINE_DB")
check_exit "$BASELINE_DB"
BASELINE_DB=${BASELINE_DB:-$DEFAULT_BASELINE_DB}
# 如果输入的是目录，自动添加默认文件名
if [[ -d "$BASELINE_DB" ]] 2>/dev/null; then
  BASELINE_DB="${BASELINE_DB%/}/baseline.db"
fi
# 检查基线数据库文件是否存在
if [[ ! -f "$BASELINE_DB" ]]; then
  echo "$MSG_ERROR_BASELINE_NOT_FOUND" >&2
  exit 1
fi

read -erp "$MSG_CURRENT_PROMPT [${DEFAULT_CURRENT_DB}]: " CURRENT_DB
CURRENT_DB=$(clean_input "$CURRENT_DB")
check_exit "$CURRENT_DB"
CURRENT_DB=${CURRENT_DB:-$DEFAULT_CURRENT_DB}
# 如果输入的是目录，自动添加默认文件名
if [[ -d "$CURRENT_DB" ]] 2>/dev/null; then
  CURRENT_DB="${CURRENT_DB%/}/current.db"
fi
# 检查当前数据库文件是否存在
if [[ ! -f "$CURRENT_DB" ]]; then
  echo "$MSG_ERROR_CURRENT_NOT_FOUND: $CURRENT_DB" >&2
  exit 1
fi

read -erp "$MSG_OUTPUT_PROMPT [${DEFAULT_REPORT_DIR}/]: " OUTPUT_PATH
OUTPUT_PATH=$(clean_input "$OUTPUT_PATH")
check_exit "$OUTPUT_PATH"
OUTPUT_PATH=${OUTPUT_PATH:-${DEFAULT_REPORT_DIR}/diff}
# 如果输出路径是目录，添加默认文件名
if [[ -d "$OUTPUT_PATH" ]] 2>/dev/null; then
  OUTPUT_PATH="${OUTPUT_PATH%/}/diff.csv"
fi

CMD=(python -m ks_prov_compare.compare_cli compare --baseline "$BASELINE_DB" --current "$CURRENT_DB" --output "$OUTPUT_PATH")

echo "$MSG_EXECUTING ${CMD[*]}"
"${CMD[@]}"

