#!/bin/bash

# setup-config.sh - syntaxis Configuration Helper
# Helps users interactively configure syntaxis applications

set -e

# Colors
BLUE='\033[0;34m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

CONFIG_DIR="${SYNTAXIS_CONFIG_DIR:-$HOME/.config/syntaxis}"
INTERACTIVE=false

# Functions
log_info() {
  echo -e "${BLUE}ℹ${NC} $1"
}

log_success() {
  echo -e "${GREEN}✓${NC} $1"
}

log_warn() {
  echo -e "${YELLOW}⚠${NC} $1"
}

# Parse arguments
while [[ $# -gt 0 ]]; do
  case $1 in
    --interactive)
      INTERACTIVE=true
      shift
      ;;
    --config-dir)
      CONFIG_DIR="$2"
      shift 2
      ;;
    --help)
      cat << 'EOF'
syntaxis Configuration Helper

Usage: ./setup-config.sh [OPTIONS]

Options:
  --interactive     Interactive configuration mode
  --config-dir DIR  Configuration directory (default: ~/.config/syntaxis)
  --help            Show this help message

Examples:
  ./setup-config.sh --interactive
  ./setup-config.sh --config-dir ~/.config/my-syntaxis

This script helps configure syntaxis applications:
  - syntaxis-cli
  - syntaxis-tui
  - syntaxis-api

EOF
      exit 0
      ;;
    *)
      echo "Unknown option: $1"
      exit 1
      ;;
  esac
done

# Ensure config directory exists
mkdir -p "$CONFIG_DIR"

# CLI Configuration
configure_cli() {
  log_info "Configuring syntaxis-cli..."

  local cli_config="$CONFIG_DIR/syntaxis-cli.toml"

  if [ -f "$cli_config" ]; then
    log_warn "syntaxis-cli.toml already exists"
    if [ "$INTERACTIVE" = true ]; then
      read -p "Overwrite existing config? (y/n) " -n 1 -r
      echo
      if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        log_info "Skipped CLI configuration"
        return
      fi
    else
      log_info "Skipped CLI configuration (use --interactive to overwrite)"
      return
    fi
  fi

  # Create config
  cat > "$cli_config" << 'EOF'
[general]
# Output format: table, json, yaml, plain
output_format = "table"

# Verbose output
verbose = false

# Use colors
use_colors = true

[database]
# Database backend: sqlite (default) or surrealdb
backend = "sqlite"

# SQLite path (relative to SYNTAXIS_DATA_DIR)
sqlite_path = "syntaxis.db"

[pagination]
# Items per page
items_per_page = 20
EOF

  log_success "CLI configuration created"
}

# TUI Configuration
configure_tui() {
  log_info "Configuring syntaxis-tui..."

  local tui_config="$CONFIG_DIR/syntaxis-tui.toml"

  if [ -f "$tui_config" ]; then
    log_warn "syntaxis-tui.toml already exists"
    if [ "$INTERACTIVE" = true ]; then
      read -p "Overwrite existing config? (y/n) " -n 1 -r
      echo
      if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        log_info "Skipped TUI configuration"
        return
      fi
    else
      log_info "Skipped TUI configuration (use --interactive to overwrite)"
      return
    fi
  fi

  # Create config
  cat > "$tui_config" << 'EOF'
[keybindings]
# vim-style navigation
move_up = "k"
move_down = "j"
move_left = "h"
move_right = "l"

# Actions
select = "Enter"
insert = "i"
edit = "e"
delete = "d"
save = ":w"
quit = ":q"
search = "/"

[colors]
# Theme: dark, light, solarized
theme = "dark"

[behavior]
# Enable mouse
enable_mouse = true

# Auto-save
auto_save = true

# Confirm before delete
confirm_delete = true
EOF

  log_success "TUI configuration created"
}

# API Configuration
configure_api() {
  log_info "Configuring syntaxis-api..."

  local api_config="$CONFIG_DIR/syntaxis-api.toml"

  if [ -f "$api_config" ]; then
    log_warn "syntaxis-api.toml already exists"
    if [ "$INTERACTIVE" = true ]; then
      read -p "Overwrite existing config? (y/n) " -n 1 -r
      echo
      if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        log_info "Skipped API configuration"
        return
      fi
    else
      log_info "Skipped API configuration (use --interactive to overwrite)"
      return
    fi
  fi

  # Create config
  cat > "$api_config" << 'EOF'
[server]
# Server address and port
host = "127.0.0.1"
port = 3000

# CORS settings
cors_enabled = true
cors_origins = ["http://localhost:3000", "http://localhost:8080"]

# Request logging
log_requests = true

[database]
# Backend: sqlite (default) or surrealdb
backend = "sqlite"

[database.sqlite]
# Database path
path = "syntaxis.db"

# Connection pool
pool_size = 5

# WAL mode
wal_mode = true

[features]
# Feature flags
auth_enabled = false
metrics_enabled = true
logging_enabled = true
EOF

  log_success "API configuration created"
}

# Database Configuration
configure_database() {
  log_info "Configuring database..."

  local db_config="$CONFIG_DIR/database-default.toml"

  if [ -f "$db_config" ]; then
    log_info "SQLite config already exists"
  else
    # Create SQLite config
    cat > "$db_config" << 'EOF'
[database]
type = "sqlite"
path = "syntaxis.db"

[database.connection]
pool_size = 5
max_connections = 20
wal_mode = true
journal_mode = "WAL"
synchronous = "NORMAL"

[migrations]
auto_migrate = true
EOF

    log_success "SQLite configuration created"
  fi

  # SurrealDB config (optional)
  local sdb_config="$CONFIG_DIR/database-surrealdb.toml"

  if [ ! -f "$sdb_config" ]; then
    cat > "$sdb_config" << 'EOF'
[database]
type = "surrealdb"
url = "file:///tmp/syntaxis.db"
# For remote: url = "http://localhost:8000"

namespace = "syntaxis"
database = "syntaxis"

[credentials]
username = "root"
password = "root"

[connection]
pool_size = 10
timeout = 30
EOF

    log_info "SurrealDB config template created (optional)"
  fi
}

# Interactive Setup
interactive_setup() {
  echo ""
  echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
  echo "syntaxis Configuration Setup"
  echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
  echo ""
  echo "Configuration directory: $CONFIG_DIR"
  echo ""

  read -p "Configure syntaxis-cli? (y/n) " -n 1 -r
  echo
  if [[ $REPLY =~ ^[Yy]$ ]]; then
    configure_cli
  fi

  echo ""
  read -p "Configure syntaxis-tui? (y/n) " -n 1 -r
  echo
  if [[ $REPLY =~ ^[Yy]$ ]]; then
    configure_tui
  fi

  echo ""
  read -p "Configure syntaxis-api? (y/n) " -n 1 -r
  echo
  if [[ $REPLY =~ ^[Yy]$ ]]; then
    configure_api
  fi

  echo ""
  read -p "Configure database? (y/n) " -n 1 -r
  echo
  if [[ $REPLY =~ ^[Yy]$ ]]; then
    configure_database
  fi
}

# Auto Setup (non-interactive)
auto_setup() {
  log_info "Setting up default configuration..."
  configure_cli
  configure_tui
  configure_api
  configure_database
}

# Main
main() {
  echo ""
  echo "syntaxis Configuration Helper"
  echo ""

  if [ "$INTERACTIVE" = true ]; then
    interactive_setup
  else
    auto_setup
  fi

  echo ""
  echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
  log_success "Configuration setup complete"
  echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
  echo ""
  echo "Configuration files in: $CONFIG_DIR"
  echo ""
  echo "Next steps:"
  echo "  1. Review config files: ls $CONFIG_DIR"
  echo "  2. Edit if needed: nano $CONFIG_DIR/syntaxis-cli.toml"
  echo "  3. Set environment: export SYNTAXIS_CONFIG_DIR=$CONFIG_DIR"
  echo "  4. Run syntaxis: syntaxis-cli --version"
  echo ""
}

main
