#!/bin/bash
# Haven Grazuri Accounting System - Production Deployment
# Simple deployment script for cPanel/production environment

echo "=========================================="
echo "Accounting System Production Deployment"
echo "=========================================="
echo ""

# Step 1: Run migrations
echo "[1/5] Running database migrations..."
python manage.py makemigrations accounting
python manage.py migrate

if [ $? -ne 0 ]; then
    echo "ERROR: Migrations failed. Please check your database connection."
    echo "Make sure your .env file or settings.py has correct database credentials."
    exit 1
fi

echo "[+] Migrations completed"
echo ""

# Step 2: Create Chart of Accounts
echo "[2/5] Creating Chart of Accounts..."
python manage.py shell << 'EOF'
import os
import django
from decimal import Decimal
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

try:
    from accounting.models import Account
    from users.models import CustomUser

    system_user = CustomUser.objects.filter(role='admin').first()

    accounts_data = [
        # ASSETS
        {'code': '202001', 'name': 'Loan Portfolio - Principal', 'account_type': 'asset', 'subtype': 'loan_portfolio', 'description': 'Outstanding principal balance', 'is_system_account': True},
        {'code': '202002', 'name': 'Accrued Interest Receivable', 'account_type': 'asset', 'subtype': 'current_asset', 'description': 'Interest earned but not collected', 'is_system_account': True},
        {'code': '202003', 'name': 'Cash on Hand', 'account_type': 'asset', 'subtype': 'current_asset', 'description': 'Physical cash in branches', 'is_system_account': True},
        {'code': '202004', 'name': 'Bank Account - Main', 'account_type': 'asset', 'subtype': 'current_asset', 'description': 'Main bank account', 'is_system_account': True},
        {'code': '202005', 'name': 'M-Pesa Account', 'account_type': 'asset', 'subtype': 'current_asset', 'description': 'M-Pesa business account', 'is_system_account': True},
        {'code': '202006', 'name': 'Allowance for Loan Losses', 'account_type': 'asset', 'subtype': 'loan_portfolio', 'description': 'Reserve for loan defaults', 'is_system_account': True},
        
        # LIABILITIES
        {'code': '302001', 'name': 'Client Savings Deposits', 'account_type': 'liability', 'subtype': 'client_savings', 'description': 'Client savings', 'is_system_account': True},
        {'code': '302003', 'name': 'Accrued Expenses Payable', 'account_type': 'liability', 'subtype': 'current_liability', 'description': 'Expenses incurred not paid', 'is_system_account': True},
        
        # EQUITY
        {'code': '320001', 'name': 'Share Capital', 'account_type': 'equity', 'subtype': None, 'description': 'Owner investment', 'is_system_account': True},
        {'code': '320002', 'name': 'Retained Earnings', 'account_type': 'equity', 'subtype': None, 'description': 'Accumulated profits', 'is_system_account': True},
        {'code': '320003', 'name': 'Current Year Earnings', 'account_type': 'equity', 'subtype': None, 'description': 'Current year profit', 'is_system_account': True},
        
        # INCOME
        {'code': '401001', 'name': 'Interest Income - Loans', 'account_type': 'income', 'subtype': 'interest_income', 'description': 'Loan interest income', 'is_system_account': True},
        {'code': '401002', 'name': 'Fee Income - Processing Fees', 'account_type': 'income', 'subtype': 'fee_income', 'description': 'Processing fees', 'is_system_account': True},
        {'code': '401003', 'name': 'Fee Income - Late Payment', 'account_type': 'income', 'subtype': 'fee_income', 'description': 'Late payment penalties', 'is_system_account': True},
        
        # EXPENSES
        {'code': '501001', 'name': 'Salaries and Wages', 'account_type': 'expense', 'subtype': 'staff_costs', 'description': 'Staff salaries', 'is_system_account': True},
        {'code': '501002', 'name': 'Rent Expense', 'account_type': 'expense', 'subtype': 'operating_expense', 'description': 'Office rent', 'is_system_account': False},
        {'code': '501003', 'name': 'Utilities Expense', 'account_type': 'expense', 'subtype': 'operating_expense', 'description': 'Utilities', 'is_system_account': False},
        {'code': '501007', 'name': 'Loan Loss Provision', 'account_type': 'expense', 'subtype': 'loan_loss_provision', 'description': 'Loan loss provisions', 'is_system_account': True},
    ]

    created = 0
    existing = 0
    
    for data in accounts_data:
        acc, is_new = Account.objects.get_or_create(
            code=data['code'],
            defaults={
                'name': data['name'],
                'account_type': data['account_type'],
                'subtype': data['subtype'],
                'description': data['description'],
                'is_system_account': data['is_system_account'],
                'is_active': True,
                'created_by': system_user
            }
        )
        if is_new:
            created += 1
            print(f"[+] Created: {acc.code} - {acc.name}")
        else:
            existing += 1

    print(f"\nChart of Accounts: {created} created, {existing} already existed")
    
except Exception as e:
    print(f"ERROR: {str(e)}")
    exit(1)
EOF

echo ""

# Step 3: Create Fiscal Periods
echo "[3/5] Creating fiscal periods..."
python manage.py shell << 'EOF'
import os
import django
from datetime import datetime, timedelta
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

try:
    from accounting.models import FiscalPeriod

    year = datetime.now().year
    created = 0
    existing = 0

    # Monthly periods
    for month in range(1, 13):
        start = datetime(year, month, 1).date()
        if month == 12:
            end = datetime(year, 12, 31).date()
        else:
            end = (datetime(year, month + 1, 1) - timedelta(days=1)).date()
        
        period, is_new = FiscalPeriod.objects.get_or_create(
            start_date=start,
            end_date=end,
            defaults={
                'name': start.strftime('%B %Y'),
                'period_type': 'monthly',
                'status': 'open'
            }
        )
        if is_new:
            created += 1

    # Annual period
    period, is_new = FiscalPeriod.objects.get_or_create(
        name=f'FY {year}',
        period_type='annual',
        defaults={
            'start_date': datetime(year, 1, 1).date(),
            'end_date': datetime(year, 12, 31).date(),
            'status': 'open'
        }
    )
    if is_new:
        created += 1

    print(f"Fiscal Periods: {created} created")
    
except Exception as e:
    print(f"ERROR: {str(e)}")
    exit(1)
EOF

echo ""

# Step 4: Collect static files
echo "[4/5] Collecting static files..."
python manage.py collectstatic --noinput

echo ""

# Step 5: Verify installation
echo "[5/5] Verifying installation..."
python manage.py shell << 'EOF'
from accounting.models import Account, FiscalPeriod
print(f"[+] Accounts created: {Account.objects.count()}")
print(f"[+] Fiscal periods: {FiscalPeriod.objects.count()}")
print(f"[+] Active accounts: {Account.objects.filter(is_active=True).count()}")
EOF

echo ""
echo "=========================================="
echo "Deployment Complete!"
echo "=========================================="
echo ""
echo "Next Steps:"
echo "1. Access accounting: /accounting/dashboard/"
echo "2. Configure user permissions"
echo "3. Test loan integration"
echo ""
