#!/bin/bash
# =============================================================
# Setup Script — SiAkun Pengadaan
# Sistem Akuntansi Pengadaan Barang & Jasa (PSAK 72)
# =============================================================

set -e

echo ""
echo "╔══════════════════════════════════════════════════════╗"
echo "║       SiAkun Pengadaan — Setup Script               ║"
echo "║       PSAK 72 Compliant Accounting System           ║"
echo "╚══════════════════════════════════════════════════════╝"
echo ""

# 1. Cek Python
echo "▶ Memeriksa Python..."
if ! command -v python3 &> /dev/null; then
    echo "✗ Python3 tidak ditemukan. Install Python 3.9+ terlebih dahulu."
    exit 1
fi
python3 --version

# 2. Cek PostgreSQL
echo ""
echo "▶ Memeriksa PostgreSQL..."
if ! command -v psql &> /dev/null; then
    echo "✗ PostgreSQL tidak ditemukan."
    echo "  Ubuntu/Debian : sudo apt install postgresql postgresql-contrib"
    echo "  macOS         : brew install postgresql"
    echo "  Windows       : Download dari https://www.postgresql.org/download/"
    exit 1
fi
echo "✓ PostgreSQL ditemukan"

# 3. Buat virtual environment
echo ""
echo "▶ Membuat virtual environment..."
if [ ! -d "venv" ]; then
    python3 -m venv venv
    echo "✓ Virtual environment dibuat"
else
    echo "✓ Virtual environment sudah ada"
fi

# 4. Aktivasi venv
source venv/bin/activate

# 5. Install dependencies
echo ""
echo "▶ Menginstall dependensi Python..."
pip install --upgrade pip -q
pip install -r requirements.txt -q
echo "✓ Dependensi terinstall"

# 6. Salin .env jika belum ada
if [ ! -f ".env" ]; then
    cp .env.example .env 2>/dev/null || true
fi

# 7. Buat database PostgreSQL
echo ""
echo "▶ Menyiapkan database PostgreSQL..."
echo "  (Masukkan password PostgreSQL jika diminta)"
DB_NAME="procurement_accounting"
DB_USER="postgres"

if psql -U $DB_USER -lqt 2>/dev/null | cut -d \| -f 1 | grep -qw $DB_NAME; then
    echo "✓ Database '$DB_NAME' sudah ada"
else
    createdb -U $DB_USER $DB_NAME 2>/dev/null && echo "✓ Database '$DB_NAME' dibuat" || \
    echo "! Tidak bisa membuat database otomatis. Buat manual: createdb -U postgres procurement_accounting"
fi

# 8. Inisialisasi tabel & data awal
echo ""
echo "▶ Membuat tabel dan data awal..."
flask --app run.py init-db

echo ""
echo "╔══════════════════════════════════════════════════════╗"
echo "║   ✓ Setup selesai! Jalankan aplikasi:               ║"
echo "║                                                      ║"
echo "║     source venv/bin/activate                        ║"
echo "║     python run.py                                   ║"
echo "║                                                      ║"
echo "║   Buka browser: http://localhost:5000               ║"
echo "║   Login: admin / admin123                           ║"
echo "╚══════════════════════════════════════════════════════╝"
echo ""
