#!/bin/bash
set -e

echo "=========================================="
echo "  AegisOne Fix & Deploy Script"
echo "=========================================="

# 1. Импортировать схему в PostgreSQL
echo ""
echo "[1/7] Импорт схемы в PostgreSQL..."
if [ -f /tmp/schema.sql ]; then
    docker exec -i aegisone-postgres psql -U aegisone -d aegisone < /tmp/schema.sql
    echo "  ✅ Схема импортирована"
else
    echo "  ❌ /tmp/schema.sql не найден"
    exit 1
fi

# 2. Импортировать seed-данные
echo ""
echo "[2/7] Импорт seed-данных..."
if [ -f /tmp/seed.sql ]; then
    docker exec -i aegisone-postgres psql -U aegisone -d aegisone < /tmp/seed.sql
    echo "  ✅ Seed-данные импортированы"
else
    echo "  ❌ /tmp/seed.sql не найден"
    exit 1
fi

# 3. Проверить таблицы
echo ""
echo "[3/7] Проверка таблиц..."
TABLE_COUNT=$(docker exec aegisone-postgres psql -U aegisone -d aegisone -t -c "SELECT count(*) FROM information_schema.tables WHERE table_schema='public';")
echo "  Найдено таблиц: $TABLE_COUNT"

# 4. Сгенерировать bcrypt-хеш и обновить пароль
echo ""
echo "[4/7] Генерация валидного bcrypt-хеша..."
HASH=$(python3 -c "
from passlib.context import CryptContext
ctx = CryptContext(schemes=['bcrypt'], deprecated='auto')
print(ctx.hash('AegisOne2024!'))
" 2>/dev/null || echo "ERROR")

if [ "$HASH" = "ERROR" ] || [ -z "$HASH" ]; then
    echo "  ⚠️ passlib не установлен, используем альтернативный метод..."
    HASH=$(python3 -c "
import bcrypt
password = b'AegisOne2024!'
salt = bcrypt.gensalt()
hashed = bcrypt.hashpw(password, salt)
print(hashed.decode())
" 2>/dev/null || echo "ERROR2")
fi

if [ "$HASH" != "ERROR" ] && [ "$HASH" != "ERROR2" ]; then
    docker exec aegisone-postgres psql -U aegisone -d aegisone -c "
    UPDATE users SET password_hash='$HASH' WHERE login='owner';
    "
    echo "  ✅ Пароль обновлен (логин: owner, пароль: AegisOne2024!)"
else
    echo "  ❌ Не удалось сгенерировать хеш"
    exit 1
fi

# 5. Копирование CSS
echo ""
echo "[5/7] Копирование CSS..."
mkdir -p /opt/projects/aegisone-py/app/static/css
cp /opt/projects/aegisone-php/src/assets/css/style.css /opt/projects/aegisone-py/app/static/css/service.css
echo "  ✅ CSS скопирован"

# 6. Исправить шаблон login.html
echo ""
echo "[6/7] Исправление шаблона login.html..."
cat > /opt/projects/aegisone-py/app/templates/login.html << 'TEMPLATE'
{% extends "base.html" %}
{% block body_class %}login-page{% endblock %}
{% block content %}
<link rel="stylesheet" href="/static/css/service.css">
<div class="login-box">
    <div class="login-brand">
        <img src="/logo.php" alt="AegisOne" class="login-brand__img">
        <div class="login-brand__title">AegisOne Engineering</div>
        <div class="login-brand__subtitle">Service Portal</div>
    </div>
    <div class="login-divider"></div>
    <h1>Вход в сервисный портал</h1>
    {% if error %}
    <div class="alert alert-error">{{ error }}</div>
    {% endif %}
    <form method="post">
        <div class="form-group">
            <label for="login">Логин</label>
            <input type="text" id="login" name="login" placeholder="Введите логин" required autocomplete="username" autofocus>
        </div>
        <div class="form-group">
            <label for="password">Пароль</label>
            <input type="password" id="password" name="password" placeholder="Введите пароль" required autocomplete="current-password">
        </div>
        <button type="submit" class="btn btn-primary btn-block">Войти</button>
    </form>
    <p class="login-box__footnote">* Сервисный портал для сотрудников AegisOne Engineering</p>
</div>
{% endblock %}
TEMPLATE
echo "  ✅ Шаблон исправлен"

# 7. Исправить main.py - добавить StaticFiles
echo ""
echo "[7/7] Исправление main.py..."
sed -i 's/from fastapi.staticfiles import StaticFiles/from fastapi.staticfiles import StaticFiles\nfrom pathlib import Path/' /opt/projects/aegisone-py/app/main.py

# Проверить, есть ли уже mount static
if ! grep -q "app.mount.*static" /opt/projects/aegisone-py/app/main.py; then
    # Добавить после templates = Jinja2Templates(...)
    sed -i '/templates = Jinja2Templates/a\
app.mount("/static", StaticFiles(directory="app/static"), name="static")' /opt/projects/aegisone-py/app/main.py
    echo "  ✅ StaticFiles добавлен"
else
    echo "  ℹ️ StaticFiles уже есть"
fi

# 8. Перезапуск
echo ""
echo "[8/8] Перезапуск приложения..."
cd /opt/projects/aegisone-py
docker compose restart app
sleep 5

# 9. Проверка
echo ""
echo "=========================================="
echo "  Проверка работоспособности"
echo "=========================================="

HEALTH=$(curl -s http://localhost:8000/health 2>/dev/null || echo "FAILED")
echo "Health check: $HEALTH"

LOGIN=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:8000/service/login 2>/dev/null || echo "FAILED")
echo "Login page: HTTP $LOGIN"

echo ""
echo "=========================================="
echo "  Готово!"
echo "=========================================="
echo ""
echo "Логин: owner"
echo "Пароль: AegisOne2024!"
echo ""
echo "URL: http://81.177.141.34:8000/service/login"
echo ""
