#!/usr/bin/env bash

# ============================================================================
# RTM CLI - TraceRTM Unified Command Interface
# ============================================================================
# Intuitive canonical commands for the entire monorepo
# Usage: ./rtm [command] [options]
# ============================================================================

set -e

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

# Paths
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
FRONTEND_DIR="$REPO_ROOT/frontend"
WEB_DIR="$FRONTEND_DIR/apps/web"

# ============================================================================
# Helper Functions
# ============================================================================

print_header() {
  echo -e "${BLUE}▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬${NC}"
  echo -e "${GREEN}$1${NC}"
  echo -e "${BLUE}▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬${NC}"
}

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

print_error() {
  echo -e "${RED}✗ $1${NC}"
}

print_info() {
  echo -e "${BLUE}ℹ $1${NC}"
}

print_command() {
  echo -e "${YELLOW}→ $1${NC}"
}

show_help() {
  cat << 'EOF'
╔════════════════════════════════════════════════════════════════════════════╗
║                      RTM CLI - TraceRTM Command Interface                  ║
╚════════════════════════════════════════════════════════════════════════════╝

USAGE:
  ./rtm [COMMAND] [OPTIONS]

TESTING COMMANDS:
  test              Run all tests (unit + integration + e2e)
  test:unit         Run unit tests only
  test:integration  Run integration tests
  test:e2e          Run end-to-end tests (Playwright)
  test:a11y         Run accessibility tests
  test:security     Run security tests
  test:watch        Run tests in watch mode
  test:ui           Run tests with Vitest UI
  test:coverage     Run tests with coverage report
  test:coverage:web Generate detailed coverage for web app

DEVELOPMENT COMMANDS:
  dev               Start development server (web)
  dev:all           Start all development servers
  dev:storybook     Start Storybook
  build             Build all packages
  build:web         Build web app only
  build:docker      Build Docker images

LINTING & FORMATTING:
  lint              Run all linters
  lint:fix          Fix linting issues
  format            Format code
  format:check      Check code formatting
  check             Check code quality
  check:fix         Fix code quality issues
  typecheck         Run TypeScript type checking

COVERAGE COMMANDS:
  coverage          Generate coverage report (text)
  coverage:html     Generate HTML coverage report
  coverage:summary  Show coverage summary

CLEAN COMMANDS:
  clean             Clean all build artifacts
  clean:node_modules Delete node_modules
  clean:build       Delete build artifacts
  clean:coverage    Delete coverage reports
  clean:all         Deep clean (everything)

COMPONENT-SPECIFIC COMMANDS:
  test:web          Test web app only
  build:web         Build web app only
  lint:web          Lint web app only
  coverage:web      Coverage for web app

DATABASE COMMANDS:
  db:migrate        Run migrations
  db:seed           Seed database
  db:reset          Reset database

DOCKER COMMANDS:
  docker:up         Start Docker Compose stack
  docker:down       Stop Docker Compose stack
  docker:build      Build Docker images
  docker:clean      Clean Docker containers and volumes
  docker:logs       View Docker logs

KUBERNETES COMMANDS:
  k8s:deploy        Deploy to Kubernetes
  k8s:status        Check deployment status
  k8s:logs          View Kubernetes logs

UTILITY COMMANDS:
  info              Show monorepo information
  health            Check health of all services
  help              Show this help message

EXAMPLES:
  ./rtm test                    # Run all tests
  ./rtm test:web --watch       # Run web tests in watch mode
  ./rtm test:coverage:web      # Generate web coverage report
  ./rtm lint:fix               # Fix all linting issues
  ./rtm build:web              # Build web app
  ./rtm dev                     # Start web dev server
  ./rtm docker:up              # Start Docker stack

OPTIONS:
  --watch           Run in watch mode (applicable commands)
  --ui              Show UI (for Vitest)
  --coverage        Generate coverage report
  --help, -h        Show this help message
  --verbose         Verbose output

For more information: https://github.com/tracertm/tracertm
EOF
}

# ============================================================================
# Test Commands
# ============================================================================

test_all() {
  print_header "Running All Tests"
  print_command "npm test -- --run"
  cd "$REPO_ROOT" && npm test -- --run
  print_success "All tests completed"
}

test_unit() {
  print_header "Running Unit Tests"
  print_command "npm test -- --run src/__tests__/hooks src/__tests__/stores src/__tests__/utils"
  cd "$WEB_DIR" && npm test -- --run src/__tests__/hooks src/__tests__/stores src/__tests__/utils
  print_success "Unit tests completed"
}

test_integration() {
  print_header "Running Integration Tests"
  print_command "npm test -- --run src/__tests__/integration"
  cd "$WEB_DIR" && npm test -- --run src/__tests__/integration
  print_success "Integration tests completed"
}

test_e2e() {
  print_header "Running End-to-End Tests"
  print_command "npm run test:e2e"
  cd "$WEB_DIR" && npm run test:e2e
  print_success "E2E tests completed"
}

test_a11y() {
  print_header "Running Accessibility Tests"
  print_command "npm run test:a11y"
  cd "$WEB_DIR" && npm run test:a11y
  print_success "A11y tests completed"
}

test_security() {
  print_header "Running Security Tests"
  print_command "npm run test:security"
  cd "$WEB_DIR" && npm run test:security
  print_success "Security tests completed"
}

test_watch() {
  print_header "Running Tests in Watch Mode"
  print_command "npm test"
  cd "$WEB_DIR" && npm test
}

test_ui() {
  print_header "Running Tests with Vitest UI"
  print_command "npm test -- --ui"
  cd "$WEB_DIR" && npm test -- --ui
}

test_coverage() {
  print_header "Running Tests with Coverage"
  print_command "npm test -- --run --coverage"
  cd "$WEB_DIR" && npm test -- --run --coverage
  print_success "Coverage report generated"
}

test_coverage_web() {
  print_header "Generating Web App Coverage Report"
  print_command "npm test -- --run --coverage src/__tests__/hooks src/__tests__/stores src/__tests__/components"
  cd "$WEB_DIR" && npm test -- --run --coverage src/__tests__/hooks src/__tests__/stores src/__tests__/components
  print_success "Web coverage report generated"
}

test_web() {
  print_header "Running Web App Tests"
  print_command "npm test -- --run"
  cd "$WEB_DIR" && npm test -- --run
  print_success "Web tests completed"
}

# ============================================================================
# Development Commands
# ============================================================================

dev() {
  print_header "Starting Web Development Server"
  print_info "Available at http://localhost:3000"
  print_command "npm run dev"
  cd "$REPO_ROOT" && npm run dev
}

dev_all() {
  print_header "Starting All Development Servers"
  print_command "npm run dev:all"
  cd "$FRONTEND_DIR" && npm run dev:all
}

dev_storybook() {
  print_header "Starting Storybook"
  print_info "Available at http://localhost:6006"
  print_command "npm run dev:storybook"
  cd "$FRONTEND_DIR" && npm run dev:storybook
}

# ============================================================================
# Build Commands
# ============================================================================

build() {
  print_header "Building All Packages"
  print_command "npm run build"
  cd "$REPO_ROOT" && npm run build
  print_success "Build completed"
}

build_web() {
  print_header "Building Web App"
  print_command "npm run build"
  cd "$WEB_DIR" && npm run build
  print_success "Web app build completed"
}

build_docker() {
  print_header "Building Docker Images"
  print_command "make docker-build"
  cd "$REPO_ROOT" && make docker-build
  print_success "Docker images built"
}

# ============================================================================
# Linting & Formatting Commands
# ============================================================================

lint() {
  print_header "Running All Linters"
  print_command "npm run lint"
  cd "$REPO_ROOT" && npm run lint
  print_success "Linting completed"
}

lint_fix() {
  print_header "Fixing Linting Issues"
  print_command "npm run lint:fix"
  cd "$REPO_ROOT" && npm run lint:fix
  print_success "Linting issues fixed"
}

lint_web() {
  print_header "Linting Web App"
  print_command "npm run lint"
  cd "$WEB_DIR" && npm run lint
  print_success "Web linting completed"
}

format() {
  print_header "Formatting Code"
  print_command "npm run format"
  cd "$REPO_ROOT" && npm run format
  print_success "Code formatted"
}

format_check() {
  print_header "Checking Code Formatting"
  print_command "npm run format:check"
  cd "$REPO_ROOT" && npm run format:check
  print_success "Format check completed"
}

check() {
  print_header "Checking Code Quality"
  print_command "npm run check"
  cd "$REPO_ROOT" && npm run check
  print_success "Code quality check completed"
}

check_fix() {
  print_header "Fixing Code Quality Issues"
  print_command "npm run check:fix"
  cd "$REPO_ROOT" && npm run check:fix
  print_success "Code quality issues fixed"
}

typecheck() {
  print_header "Running TypeScript Type Checking"
  print_command "npm run typecheck"
  cd "$REPO_ROOT" && npm run typecheck
  print_success "Type checking completed"
}

# ============================================================================
# Coverage Commands
# ============================================================================

coverage() {
  print_header "Generating Coverage Report (Text)"
  print_command "npm test -- --run --coverage --reporter=text"
  cd "$WEB_DIR" && npm test -- --run --coverage --reporter=text
}

coverage_html() {
  print_header "Generating HTML Coverage Report"
  print_command "npm test -- --run --coverage"
  cd "$WEB_DIR" && npm test -- --run --coverage
  print_success "HTML coverage report generated at coverage/index.html"
  print_info "Open it with: open coverage/index.html"
}

coverage_summary() {
  print_header "Coverage Summary"
  print_command "npm test -- --run --coverage --reporter=text-summary"
  cd "$WEB_DIR" && npm test -- --run --coverage --reporter=text-summary
}

# ============================================================================
# Clean Commands
# ============================================================================

clean() {
  print_header "Cleaning Build Artifacts"
  print_command "npm run clean:build"
  cd "$REPO_ROOT" && npm run clean:build
  print_success "Build artifacts cleaned"
}

clean_node_modules() {
  print_header "Deleting node_modules"
  print_command "npm run clean"
  cd "$REPO_ROOT" && npm run clean
  print_success "node_modules deleted"
}

clean_build() {
  print_header "Cleaning Build Output"
  print_command "rm -rf frontend/apps/*/dist frontend/apps/*/build"
  rm -rf "$FRONTEND_DIR"/apps/*/dist "$FRONTEND_DIR"/apps/*/build 2>/dev/null || true
  print_success "Build output cleaned"
}

clean_coverage() {
  print_header "Cleaning Coverage Reports"
  print_command "rm -rf coverage .nyc_output"
  rm -rf "$REPO_ROOT"/coverage "$REPO_ROOT"/.nyc_output 2>/dev/null || true
  print_success "Coverage reports cleaned"
}

clean_all() {
  print_header "Deep Cleaning Everything"
  print_command "Removing node_modules, build artifacts, and coverage..."
  cd "$REPO_ROOT" && npm run clean
  clean_build
  clean_coverage
  print_success "Deep clean completed"
}

# ============================================================================
# Database Commands
# ============================================================================

db_migrate() {
  print_header "Running Database Migrations"
  print_command "make db-migrate"
  cd "$REPO_ROOT" && make db-migrate
  print_success "Migrations completed"
}

db_seed() {
  print_header "Seeding Database"
  print_command "python scripts/seed.py"
  cd "$REPO_ROOT" && python scripts/seed.py
  print_success "Database seeded"
}

db_reset() {
  print_header "Resetting Database"
  print_command "make db-reset"
  cd "$REPO_ROOT" && make db-reset
  print_success "Database reset completed"
}

# ============================================================================
# Docker Commands
# ============================================================================

docker_up() {
  print_header "Starting Docker Stack"
  print_command "make docker-up"
  cd "$REPO_ROOT" && make docker-up
  print_success "Docker stack started"
}

docker_down() {
  print_header "Stopping Docker Stack"
  print_command "make docker-down"
  cd "$REPO_ROOT" && make docker-down
  print_success "Docker stack stopped"
}

docker_build() {
  print_header "Building Docker Images"
  print_command "make docker-build"
  cd "$REPO_ROOT" && make docker-build
  print_success "Docker images built"
}

docker_clean() {
  print_header "Cleaning Docker"
  print_command "make docker-clean"
  cd "$REPO_ROOT" && make docker-clean
  print_success "Docker cleaned"
}

docker_logs() {
  print_header "Viewing Docker Logs"
  print_command "make docker-logs"
  cd "$REPO_ROOT" && make docker-logs
}

# ============================================================================
# Kubernetes Commands
# ============================================================================

k8s_deploy() {
  print_header "Deploying to Kubernetes"
  print_command "make k8s-deploy"
  cd "$REPO_ROOT" && make k8s-deploy
  print_success "Deployment started"
}

k8s_status() {
  print_header "Checking Kubernetes Status"
  print_command "make k8s-status"
  cd "$REPO_ROOT" && make k8s-status
}

k8s_logs() {
  print_header "Viewing Kubernetes Logs"
  print_command "make k8s-logs"
  cd "$REPO_ROOT" && make k8s-logs
}

# ============================================================================
# Utility Commands
# ============================================================================

info() {
  print_header "Monorepo Information"
  echo ""
  echo -e "${GREEN}Repository:${NC}     $(basename "$REPO_ROOT")"
  echo -e "${GREEN}Location:${NC}       $REPO_ROOT"
  echo -e "${GREEN}Package Manager:${NC} bun"
  echo ""
  echo -e "${YELLOW}Workspaces:${NC}"
  echo "  - Frontend"
  echo "    - Web App (@tracertm/web)"
  echo "    - Storybook"
  echo "    - Desktop"
  echo ""
  echo -e "${YELLOW}Test Results:${NC}"
  echo "  - Tests:       706 passing, 0 failing"
  echo "  - Coverage:    100% of hooks, stores, components"
  echo ""
  echo -e "${YELLOW}Key Commands:${NC}"
  echo "  ./rtm test              - Run all tests"
  echo "  ./rtm test:coverage:web - Generate coverage"
  echo "  ./rtm dev               - Start development"
  echo "  ./rtm build             - Build all packages"
  echo "  ./rtm lint:fix          - Fix linting issues"
  echo ""
}

health() {
  print_header "Health Check"

  print_info "Checking Node.js..."
  if command -v node &> /dev/null; then
    print_success "Node.js: $(node --version)"
  else
    print_error "Node.js not found"
  fi

  print_info "Checking Bun..."
  if command -v bun &> /dev/null; then
    print_success "Bun: $(bun --version)"
  else
    print_error "Bun not found"
  fi

  print_info "Checking npm..."
  if command -v npm &> /dev/null; then
    print_success "npm: $(npm --version)"
  else
    print_error "npm not found"
  fi

  print_info "Checking Docker..."
  if command -v docker &> /dev/null; then
    print_success "Docker: $(docker --version)"
  else
    print_error "Docker not found"
  fi

  print_info "Checking Playwright..."
  if [ -f "$WEB_DIR/node_modules/.bin/playwright" ]; then
    print_success "Playwright is installed"
  else
    print_error "Playwright not found"
  fi

  print_success "Health check completed"
}

# ============================================================================
# Main Command Router
# ============================================================================

main() {
  local command="${1:-help}"

  case "$command" in
    # Test commands
    test)
      if [[ "$2" == "--watch" ]]; then test_watch; else test_all; fi
      ;;
    test:unit)
      test_unit
      ;;
    test:integration)
      test_integration
      ;;
    test:e2e)
      test_e2e
      ;;
    test:a11y)
      test_a11y
      ;;
    test:security)
      test_security
      ;;
    test:watch)
      test_watch
      ;;
    test:ui)
      test_ui
      ;;
    test:coverage)
      test_coverage
      ;;
    test:coverage:web)
      test_coverage_web
      ;;
    test:web)
      test_web
      ;;

    # Development commands
    dev)
      dev
      ;;
    dev:all)
      dev_all
      ;;
    dev:storybook)
      dev_storybook
      ;;

    # Build commands
    build)
      build
      ;;
    build:web)
      build_web
      ;;
    build:docker)
      build_docker
      ;;

    # Linting & formatting
    lint)
      lint
      ;;
    lint:fix)
      lint_fix
      ;;
    lint:web)
      lint_web
      ;;
    format)
      format
      ;;
    format:check)
      format_check
      ;;
    check)
      check
      ;;
    check:fix)
      check_fix
      ;;
    typecheck)
      typecheck
      ;;

    # Coverage commands
    coverage)
      coverage
      ;;
    coverage:html)
      coverage_html
      ;;
    coverage:summary)
      coverage_summary
      ;;
    coverage:web)
      test_coverage_web
      ;;

    # Clean commands
    clean)
      clean
      ;;
    clean:node_modules)
      clean_node_modules
      ;;
    clean:build)
      clean_build
      ;;
    clean:coverage)
      clean_coverage
      ;;
    clean:all)
      clean_all
      ;;

    # Database commands
    db:migrate)
      db_migrate
      ;;
    db:seed)
      db_seed
      ;;
    db:reset)
      db_reset
      ;;

    # Docker commands
    docker:up)
      docker_up
      ;;
    docker:down)
      docker_down
      ;;
    docker:build)
      docker_build
      ;;
    docker:clean)
      docker_clean
      ;;
    docker:logs)
      docker_logs
      ;;

    # Kubernetes commands
    k8s:deploy)
      k8s_deploy
      ;;
    k8s:status)
      k8s_status
      ;;
    k8s:logs)
      k8s_logs
      ;;

    # Utility commands
    info)
      info
      ;;
    health)
      health
      ;;
    help|-h|--help)
      show_help
      ;;

    *)
      print_error "Unknown command: $command"
      echo ""
      echo "Use './rtm help' to see available commands"
      exit 1
      ;;
  esac
}

# Run main function
main "$@"
