#!/bin/bash

# ISO 27001 資產盤點系統 - 快速設定腳本
# 此腳本會設定好開發環境並建立必要的資料

echo "========================================="
echo "ISO 27001 資產盤點系統 - 快速設定"
echo "========================================="
echo ""

# 檢查 Python
if ! command -v python3 &> /dev/null; then
    echo "❌ 錯誤: 找不到 Python 3"
    echo "   請先安裝 Python 3.11 或更新版本"
    exit 1
fi

echo "✅ Python 版本: $(python3 --version)"

# 進入後端目錄
cd backend || exit

# 建立虛擬環境 (如果不存在)
if [ ! -d "venv" ]; then
    echo ""
    echo "📦 建立 Python 虛擬環境..."
    python3 -m venv venv
fi

# 啟動虛擬環境
echo ""
echo "🔄 啟動虛擬環境..."
source venv/bin/activate

# 安裝相依套件
echo ""
echo "📦 安裝 Python 相依套件..."
pip install -q --upgrade pip
pip install -q -r requirements.txt

# 檢查 .env 檔案
if [ ! -f ".env" ]; then
    echo ""
    echo "📝 建立 .env 檔案..."
    cat > .env << EOF
SECRET_KEY=django-insecure-dev-key-$(openssl rand -hex 32)
DEBUG=True
DATABASE_URL=postgresql://iso27001_user:iso27001_pass@localhost:5432/iso27001_db
REDIS_URL=redis://localhost:6379/0
ALLOWED_HOSTS=localhost,127.0.0.1
CORS_ALLOWED_ORIGINS=http://localhost:3000,http://127.0.0.1:3000
EOF
    echo "✅ .env 檔案已建立"
else
    echo ""
    echo "✅ .env 檔案已存在"
fi

# 建立資料庫遷移
echo ""
echo "🗄️  建立資料庫遷移檔案..."
python3 manage.py makemigrations accounts --noinput
python3 manage.py makemigrations assets --noinput
python3 manage.py makemigrations documents --noinput
python3 manage.py makemigrations controls --noinput
python3 manage.py makemigrations organizations --noinput

# 執行遷移
echo ""
echo "🗄️  執行資料庫遷移..."
python3 manage.py migrate --noinput

# 建立超級使用者 (如果不存在)
echo ""
echo "👤 建立管理員帳號..."
python3 manage.py shell << EOF
from django.contrib.auth import get_user_model
User = get_user_model()

if not User.objects.filter(username='admin').exists():
    User.objects.create_superuser(
        username='admin',
        email='admin@example.com',
        password='admin123',
        role='super_admin',
        first_name='系統',
        last_name='管理員'
    )
    print('✅ 管理員帳號已建立')
    print('   使用者名稱: admin')
    print('   密碼: admin123')
    print('   ⚠️  請記得在正式環境變更密碼！')
else:
    print('✅ 管理員帳號已存在')
EOF

# 建立測試資料
echo ""
echo "📊 建立測試資料..."
python3 manage.py shell << EOF
from django.contrib.auth import get_user_model
from assets.models import Asset

User = get_user_model()

# 建立測試使用者
if not User.objects.filter(username='john').exists():
    john = User.objects.create_user(
        username='john',
        email='john@example.com',
        password='John@123',
        role='employee',
        first_name='John',
        last_name='Doe',
        employee_id='EMP001',
        department='IT'
    )
    print('✅ 測試使用者已建立: john (密碼: John@123)')

# 建立測試資產
admin = User.objects.get(username='admin')
if Asset.objects.count() == 0:
    # 伺服器
    Asset.objects.create(
        asset_number='AST-HW-001',
        name='Web Server 01',
        description='主要網站伺服器',
        asset_type='hardware',
        asset_subtype='server',
        owner=admin,
        location='機房A-機櫃3-U10',
        confidentiality='high',
        integrity='high',
        availability='high',
        status='active',
        technical_details={
            'os': 'Ubuntu 22.04 LTS',
            'ip': '192.168.1.10',
            'cpu': '8 cores',
            'ram': '32GB'
        }
    )
    
    Asset.objects.create(
        asset_number='AST-HW-002',
        name='Database Server 01',
        description='PostgreSQL 資料庫伺服器',
        asset_type='hardware',
        asset_subtype='server',
        owner=admin,
        location='機房A-機櫃3-U15',
        confidentiality='high',
        integrity='high',
        availability='high',
        status='active',
        technical_details={
            'os': 'Ubuntu 22.04 LTS',
            'ip': '192.168.1.11',
            'cpu': '16 cores',
            'ram': '64GB'
        }
    )
    
    # 軟體
    Asset.objects.create(
        asset_number='AST-SW-001',
        name='PostgreSQL 15',
        description='PostgreSQL 資料庫管理系統',
        asset_type='software',
        asset_subtype='database',
        owner=admin,
        confidentiality='high',
        integrity='high',
        availability='high',
        status='active',
        technical_details={
            'version': '15.3',
            'license': 'PostgreSQL License'
        }
    )
    
    Asset.objects.create(
        asset_number='AST-SW-002',
        name='Django Framework',
        description='Python Web 框架',
        asset_type='software',
        asset_subtype='application',
        owner=admin,
        confidentiality='medium',
        integrity='high',
        availability='high',
        status='active',
        technical_details={
            'version': '4.2.7',
            'license': 'BSD License'
        }
    )
    
    # 資料
    Asset.objects.create(
        asset_number='AST-DA-001',
        name='客戶資料庫',
        description='客戶個人資料與交易記錄',
        asset_type='data',
        asset_subtype='database',
        owner=admin,
        confidentiality='high',
        integrity='high',
        availability='medium',
        status='active',
        technical_details={
            'records': 'approx. 10,000',
            'backup': 'daily'
        }
    )
    
    print(f'✅ 已建立 {Asset.objects.count()} 個測試資產')
else:
    print(f'✅ 資產資料已存在 ({Asset.objects.count()} 個資產)')
EOF

echo ""
echo "========================================="
echo "✅ 設定完成！"
echo "========================================="
echo ""
echo "🚀 啟動後端伺服器："
echo "   cd backend"
echo "   source venv/bin/activate"
echo "   python3 manage.py runserver"
echo ""
echo "🌐 訪問："
echo "   API: http://localhost:8000/api/"
echo "   Admin: http://localhost:8000/admin/"
echo ""
echo "🔐 管理員帳號："
echo "   使用者名稱: admin"
echo "   密碼: admin123"
echo ""
echo "👤 測試帳號："
echo "   使用者名稱: john"
echo "   密碼: John@123"
echo ""
echo "📖 詳細說明請參考："
echo "   - README.md"
echo "   - AUTH_SETUP.md"
echo "   - PROGRESS_REPORT.md"
echo ""
