#!/usr/bin/env bash
# ==============================================================================
# AI_Strategy — Quick Install & Health Check
# ==============================================================================
# Запуск: bash scripts/deploy.sh
# ==============================================================================

set -euo pipefail

PROJECT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
cd "$PROJECT_DIR"

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

echo -e "${BOLD}=== AI_Strategy — Deploy & Health Check ===${NC}"
echo "Project: $PROJECT_DIR"
echo "Date:    $(date '+%Y-%m-%d %H:%M:%S')"
echo ""

# ------------------------------------------------------------------------------
# 1. Python
# ------------------------------------------------------------------------------
echo -e "${BOLD}[1] Python${NC}"
if command -v python3 &> /dev/null; then
    echo -e "  ${GREEN}✓${NC} $(python3 --version 2>&1)"
    echo -e "  ${GREEN}✓${NC} $(which python3)"
else
    echo -e "  ${RED}✗${NC} python3 not found"
fi

# ------------------------------------------------------------------------------
# 2. Dependencies
# ------------------------------------------------------------------------------
echo -e "${BOLD}[2] Key Packages${NC}"
for pkg in numpy pandas scikit-learn xgboost lightgbm torch joblib mysql-connector-python; do
    if python3 -c "import $pkg" 2>/dev/null; then
        ver=$(python3 -c "import $pkg; print(getattr($pkg, '__version__', 'ok'))" 2>/dev/null || echo "ok")
        echo -e "  ${GREEN}✓${NC} $pkg ($ver)"
    else
        echo -e "  ${RED}✗${NC} $pkg — NOT INSTALLED"
    fi
done

# ------------------------------------------------------------------------------
# 3. .env
# ------------------------------------------------------------------------------
echo -e "${BOLD}[3] Configuration${NC}"
if [ -f .env ]; then
    echo -e "  ${GREEN}✓${NC} .env file exists"
    # Check DB password (not default)
    if grep -q "g49020007" .env 2>/dev/null; then
        echo -e "  ${YELLOW}⚠${NC} .env still has default DB password"
    fi
else
    echo -e "  ${YELLOW}⚠${NC} .env not found — copy from .env.example"
    echo "    cp .env.example .env && nano .env"
fi

# ------------------------------------------------------------------------------
# 4. Models
# ------------------------------------------------------------------------------
echo -e "${BOLD}[4] Saved Models${NC}"
MODEL_COUNT=$(find models/saved -name "*.joblib" 2>/dev/null | wc -l)
if [ "$MODEL_COUNT" -gt 0 ]; then
    echo -e "  ${GREEN}✓${NC} $MODEL_COUNT models in models/saved/"
    # Count per type
    DIR_COUNT=$(find models/saved -name "*_directional.joblib" 2>/dev/null | wc -l)
    EXP_COUNT=$(find models/saved -name "*_experts.joblib" 2>/dev/null | wc -l)
    echo -e "     ├ Directional: $DIR_COUNT"
    echo -e "     └ ExpertEnsemble: $EXP_COUNT"
else
    echo -e "  ${RED}✗${NC} No models found — run training first"
fi

# ------------------------------------------------------------------------------
# 5. Database connectivity
# ------------------------------------------------------------------------------
echo -e "${BOLD}[5] Database${NC}"
if python3 -c "
from config import DB_CONFIG
import mysql.connector
conn = mysql.connector.connect(**DB_CONFIG)
conn.close()
print('OK')
" 2>/dev/null; then
    echo -e "  ${GREEN}✓${NC} MySQL connection OK (nlbotinterface.ru:3306)"
else
    echo -e "  ${RED}✗${NC} MySQL connection FAILED — check .env and network"
fi

# ------------------------------------------------------------------------------
# 6. Monitoring output
# ------------------------------------------------------------------------------
echo -e "${BOLD}[6] Monitoring Output${NC}"
if [ -d monitoring ]; then
    MD_COUNT=$(find monitoring -name "*.md" 2>/dev/null | wc -l)
    echo -e "  ${GREEN}✓${NC} $MD_COUNT monitor files in monitoring/"
    # Show latest signals
    echo ""
    for f in monitoring/*.md; do
        [ -f "$f" ] || continue
        sig=$(grep -E '\|\s*(BUY|SELL)' "$f" 2>/dev/null | tail -1)
        if [ -n "$sig" ]; then
            ticker=$(basename "$f" _monitor.md)
            echo -e "     ${ticker^^}: ${sig}"
        fi
    done
else
    echo -e "  ${YELLOW}⚠${NC} monitoring/ directory not found"
fi

# ------------------------------------------------------------------------------
# 7. Systemd
# ------------------------------------------------------------------------------
echo -e "${BOLD}[7] Systemd${NC}"
if systemctl is-enabled ai-strategy-monitor.timer &>/dev/null 2>&1; then
    echo -e "  ${GREEN}✓${NC} ai-strategy-monitor.timer is enabled"
    systemctl status ai-strategy-monitor.timer --no-pager -l 2>&1 | grep 'Trigger:' | sed 's/^/     /'
elif systemctl is-enabled ai-strategy-monitor.service &>/dev/null 2>&1; then
    echo -e "  ${GREEN}✓${NC} ai-strategy-monitor.service is enabled"
else
    echo -e "  ${YELLOW}⚠${NC} Systemd service not installed"
    echo "    To install:"
    echo "      sudo cp .systemd/ai-strategy-monitor.service /etc/systemd/system/"
    echo "      sudo cp .systemd/ai-strategy-monitor.timer /etc/systemd/system/"
    echo "      sudo systemctl daemon-reload"
    echo "      sudo systemctl enable --now ai-strategy-monitor.timer"
fi

# ------------------------------------------------------------------------------
# Summary
# ------------------------------------------------------------------------------
echo ""
echo -e "${BOLD}=== Summary ===${NC}"
echo -e "  ${GREEN}✓${NC} Press ENTER to run a dry-run monitor check"
echo -e "  ${YELLOW}⚠${NC} Press Ctrl+C to exit"
read -r

echo ""
echo -e "${BOLD}=== Quick Test: python3 monitor.py --check ===${NC}"
python3 monitor.py --check 2>&1
