#!/bin/bash
# =============================================================================
# SmartLife Monitor - Deployment Script
# =============================================================================
# Usage: bash deploy.sh [--docker|--native]
# =============================================================================

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
DEPLOY_MODE="${1:-native}"

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

echo "=============================================="
echo " SmartLife Monitor - Deployment"
echo " Mode: $DEPLOY_MODE"
echo "=============================================="

# Check for .env file
if [ ! -f "$PROJECT_DIR/.env" ]; then
    echo -e "${YELLOW}Creating .env file from example...${NC}"
    cp "$PROJECT_DIR/backend/.env.example" "$PROJECT_DIR/.env"
    echo -e "${RED}Please edit .env file with your settings before continuing!${NC}"
    exit 1
fi

source "$PROJECT_DIR/.env"

if [ "$DEPLOY_MODE" == "--docker" ]; then
    echo -e "${GREEN}Deploying with Docker...${NC}"
    
    cd "$PROJECT_DIR/docker"
    
    # Build and start containers
    docker compose build
    docker compose up -d
    
    # Wait for services
    echo "Waiting for services to start..."
    sleep 10
    
    # Run migrations
    docker compose exec api alembic upgrade head
    
    echo -e "${GREEN}Docker deployment complete!${NC}"
    echo "API: http://localhost:8000"
    echo "Frontend: http://localhost:3000"
    
else
    echo -e "${GREEN}Deploying native installation...${NC}"
    
    # Create application user if not exists
    if ! id "smartlife" &>/dev/null; then
        useradd -m -s /bin/bash smartlife
    fi
    
    # Setup directories
    APP_DIR="/var/www/smartlife"
    mkdir -p $APP_DIR
    
    # Copy files
    echo "Copying application files..."
    cp -r "$PROJECT_DIR"/* $APP_DIR/
    chown -R smartlife:smartlife $APP_DIR
    
    # Backend setup
    echo -e "${GREEN}Setting up Backend...${NC}"
    cd $APP_DIR/backend
    
    python3.11 -m venv venv
    source venv/bin/activate
    pip install --upgrade pip
    pip install -r requirements.txt
    
    # Run migrations
    alembic upgrade head
    
    # Create initial admin user
    python3 << EOF
import asyncio
from app.database import AsyncSessionLocal, init_db
from app.models.user import User
from app.core.security import get_password_hash

async def create_admin():
    await init_db()
    async with AsyncSessionLocal() as db:
        # Check if admin exists
        from sqlalchemy import select
        result = await db.execute(select(User).where(User.email == "admin@smartlife.local"))
        if not result.scalar_one_or_none():
            admin = User(
                email="admin@smartlife.local",
                password_hash=get_password_hash("admin123"),
                full_name="System Admin",
                full_name_ar="مدير النظام",
                role="super_admin",
                language="ar",
            )
            db.add(admin)
            await db.commit()
            print("Admin user created: admin@smartlife.local / admin123")
        else:
            print("Admin user already exists")

asyncio.run(create_admin())
EOF
    
    deactivate
    
    # Frontend setup
    echo -e "${GREEN}Setting up Frontend...${NC}"
    cd $APP_DIR/frontend
    npm ci
    npm run build
    
    # Setup systemd services
    echo -e "${GREEN}Setting up systemd services...${NC}"
    
    # API Service
    cat > /etc/systemd/system/smartlife-api.service << EOF
[Unit]
Description=SmartLife API Server
After=network.target postgresql-15.service redis.service

[Service]
User=smartlife
Group=smartlife
WorkingDirectory=/var/www/smartlife/backend
Environment="PATH=/var/www/smartlife/backend/venv/bin"
EnvironmentFile=/var/www/smartlife/.env
ExecStart=/var/www/smartlife/backend/venv/bin/gunicorn app.main:app -w 4 -k uvicorn.workers.UvicornWorker -b 127.0.0.1:8000
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF

    # Celery Worker Service
    cat > /etc/systemd/system/smartlife-celery.service << EOF
[Unit]
Description=SmartLife Celery Worker
After=network.target redis.service

[Service]
User=smartlife
Group=smartlife
WorkingDirectory=/var/www/smartlife/backend
Environment="PATH=/var/www/smartlife/backend/venv/bin"
EnvironmentFile=/var/www/smartlife/.env
ExecStart=/var/www/smartlife/backend/venv/bin/celery -A app.tasks.celery_app worker -l info
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF

    # Celery Beat Service
    cat > /etc/systemd/system/smartlife-celerybeat.service << EOF
[Unit]
Description=SmartLife Celery Beat Scheduler
After=network.target redis.service smartlife-celery.service

[Service]
User=smartlife
Group=smartlife
WorkingDirectory=/var/www/smartlife/backend
Environment="PATH=/var/www/smartlife/backend/venv/bin"
EnvironmentFile=/var/www/smartlife/.env
ExecStart=/var/www/smartlife/backend/venv/bin/celery -A app.tasks.celery_app beat -l info
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF

    # Reload and start services
    systemctl daemon-reload
    systemctl enable smartlife-api smartlife-celery smartlife-celerybeat
    systemctl start smartlife-api smartlife-celery smartlife-celerybeat
    
    # Setup Nginx
    echo -e "${GREEN}Configuring Nginx...${NC}"
    cat > /etc/nginx/conf.d/smartlife.conf << 'EOF'
upstream smartlife_api {
    server 127.0.0.1:8000;
}

server {
    listen 80;
    server_name _;

    # Frontend static files
    location / {
        root /var/www/smartlife/frontend/out;
        try_files $uri $uri.html $uri/ /index.html;
    }

    # API proxy
    location /api/ {
        proxy_pass http://smartlife_api;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    # WebSocket
    location /ws/ {
        proxy_pass http://smartlife_api;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
    }
}
EOF

    # Test and reload nginx
    nginx -t
    systemctl restart nginx
    
    echo -e "${GREEN}=============================================="
    echo " Native Deployment Complete!"
    echo "=============================================="
    echo ""
    echo " Services Status:"
    systemctl status smartlife-api --no-pager -l || true
    echo ""
    echo " Access:"
    echo " - Frontend: http://your-server-ip"
    echo " - API Docs: http://your-server-ip/api/docs"
    echo ""
    echo " Default Admin Login:"
    echo " - Email: admin@smartlife.local"
    echo " - Password: admin123"
    echo ""
    echo -e "${RED} IMPORTANT: Change the default password immediately!${NC}"
    echo "=============================================="
fi
