#!/usr/bin/env bash
# deploy_linux.sh — one-shot setup for FMCG on Linux (Ubuntu/Debian)
# Usage: bash deploy_linux.sh
set -euo pipefail

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

echo "=== FMCG Compliance Tool — Linux deployment ==="
echo "Project dir: $PROJECT_DIR"

# ── 1. System packages ────────────────────────────────────────────────────────
echo ""
echo "[1/6] Installing system packages..."
sudo apt-get update -qq
sudo apt-get install -y python3 python3-pip python3-venv fonts-dejavu-core

# ── 2. Virtual environment ────────────────────────────────────────────────────
echo ""
echo "[2/6] Creating virtual environment..."
# Project needs Python 3.11+ (match/case in engine/scoring.py). Override with PY=... if needed.
PY="${PY:-python3.11}"
"$PY" -m venv .venv
source .venv/bin/activate

# ── 3. Python dependencies ────────────────────────────────────────────────────
echo ""
echo "[3/6] Installing Python dependencies..."
pip install --upgrade pip -q
pip install -r requirements.txt

# ── 4. Fonts ──────────────────────────────────────────────────────────────────
echo ""
echo "[4/6] Setting up fonts..."
python migrations/setup_fonts.py

# ── 5. Database ───────────────────────────────────────────────────────────────
echo ""
echo "[5/6] Initializing database..."
python migrations/init_db.py
python migrations/seed_data.py
python migrations/seed_users.py
python migrations/add_indexes.py
python migrations/add_fts5.py

# ── 6. Verify ─────────────────────────────────────────────────────────────────
echo ""
echo "[6/6] Verifying..."
python -m py_compile app.py engine/scoring.py export/pdf.py
python -c "
import sqlite3
c = sqlite3.connect('fmcg.db')
n = c.execute('SELECT COUNT(*) FROM requirements').fetchone()[0]
print(f'  requirements in DB: {n}')
assert n > 0, 'DB is empty!'
print('  DB OK')
"

echo ""
echo "=== Setup complete ==="
echo ""
echo "Start the app:"
echo "  source .venv/bin/activate"
echo "  streamlit run app.py --server.port 8501"
echo ""
echo "Default accounts:"
echo "  Admin:      admin@fmcg / admin123"
echo "  Expert:     expert@fmcg / expert123"
echo "  CompanyRep: rep@fmcg / rep123"
echo ""
echo "WARNING: Change passwords before production use!"
