#!/usr/bin/env python
"""
Simple Accounting System Deployment
Focuses on fixing the .env loading issue
"""

import os
import sys
from pathlib import Path

print("=" * 60)
print("Accounting System - Simple Deployment")
print("=" * 60)
print()

# Step 1: Find and load .env file
print("[1/4] Looking for .env file...")
BASE_DIR = Path(__file__).resolve().parent
env_path = BASE_DIR / '.env'

print(f"  Script location: {BASE_DIR}")
print(f"  Looking for .env at: {env_path}")
print(f"  .env exists: {env_path.exists()}")

if not env_path.exists():
    print()
    print("ERROR: .env file not found!")
    print()
    print("Please create a .env file with your database credentials:")
    print()
    print("DB_NAME=xygbfpsg_loans")
    print("DB_USER=xygbfpsg_graz")  
    print("DB_PASSWORD=your_password_here")
    print("DB_HOST=localhost")
    print("DB_PORT=3306")
    print()
    sys.exit(1)

# Load .env with override BEFORE any Django imports
from dotenv import load_dotenv
load_dotenv(env_path, override=True)

print(f"  Loaded .env file")
print(f"  DB_NAME: {os.getenv('DB_NAME', 'NOT SET')}")
print(f"  DB_USER: {os.getenv('DB_USER', 'NOT SET')}")
print(f"  DB_HOST: {os.getenv('DB_HOST', 'NOT SET')}")

# Step 2: Setup Django with explicit database configuration
print("[2/4] Setting up Django...")
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')

# CRITICAL: Override database settings directly in environment
# This ensures Django uses the correct credentials
os.environ['DB_NAME'] = os.getenv('DB_NAME', 'xygbfpsg_loans')
os.environ['DB_USER'] = os.getenv('DB_USER', 'xygbfpsg_graz')  
os.environ['DB_PASSWORD'] = os.getenv('DB_PASSWORD', '')
os.environ['DB_HOST'] = os.getenv('DB_HOST', 'localhost')
os.environ['DB_PORT'] = os.getenv('DB_PORT', '3306')

print(f"  Setting DB_USER to: {os.environ['DB_USER']}")
print(f"  Setting DB_NAME to: {os.environ['DB_NAME']}")

try:
    import django
    django.setup()
    print("  Django setup successful")
except Exception as e:
    print(f"  ERROR: Django setup failed: {e}")
    sys.exit(1)

print()

# Step 3: Create Chart of Accounts
print("[3/4] Creating Chart of Accounts...")

try:
    from accounting.models import Account
    from users.models import CustomUser
    
    system_user = CustomUser.objects.filter(role='admin').first()
    print(f"  Using admin user: {system_user.username if system_user else 'None'}")
    
    accounts = [
        {'code': '202001', 'name': 'Loan Portfolio - Principal', 'type': 'asset', 'subtype': 'loan_portfolio'},
        {'code': '202002', 'name': 'Accrued Interest Receivable', 'type': 'asset', 'subtype': 'current_asset'},
        {'code': '202003', 'name': 'Cash on Hand', 'type': 'asset', 'subtype': 'current_asset'},
        {'code': '202004', 'name': 'Bank Account - Main', 'type': 'asset', 'subtype': 'current_asset'},
        {'code': '202005', 'name': 'M-Pesa Account', 'type': 'asset', 'subtype': 'current_asset'},
        {'code': '302001', 'name': 'Client Savings Deposits', 'type': 'liability', 'subtype': 'client_savings'},
        {'code': '320001', 'name': 'Share Capital', 'type': 'equity', 'subtype': None},
        {'code': '320002', 'name': 'Retained Earnings', 'type': 'equity', 'subtype': None},
        {'code': '401001', 'name': 'Interest Income - Loans', 'type': 'income', 'subtype': 'interest_income'},
        {'code': '401002', 'name': 'Fee Income - Processing Fees', 'type': 'income', 'subtype': 'fee_income'},
        {'code': '501001', 'name': 'Salaries and Wages', 'type': 'expense', 'subtype': 'staff_costs'},
        {'code': '501007', 'name': 'Loan Loss Provision Expense', 'type': 'expense', 'subtype': 'loan_loss_provision'},
    ]
    
    created = 0
    exists = 0
    
    for acc in accounts:
        account, is_new = Account.objects.get_or_create(
            code=acc['code'],
            defaults={
                'name': acc['name'],
                'account_type': acc['type'],
                'subtype': acc['subtype'],
                'description': f"{acc['name']} account",
                'is_system_account': True,
                'is_active': True,
                'created_by': system_user
            }
        )
        if is_new:
            created += 1
            print(f"  [+] {acc['code']} - {acc['name']}")
        else:
            exists += 1
    
    print()
    print(f"  Created: {created}, Already existed: {exists}")
    
except Exception as e:
    print(f"  ERROR: {e}")
    import traceback
    traceback.print_exc()
    sys.exit(1)

print()

# Step 4: Create Fiscal Periods
print("[4/4] Creating Fiscal Periods...")

try:
    from accounting.models import FiscalPeriod
    from datetime import datetime, timedelta
    
    year = datetime.now().year
    created = 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"  Created: {created} periods")
    
except Exception as e:
    print(f"  ERROR: {e}")
    import traceback
    traceback.print_exc()
    sys.exit(1)

# Success!
print()
print("=" * 60)
print("SUCCESS! Accounting system deployed")
print("=" * 60)
print()
print(f"Accounts: {Account.objects.count()}")
print(f"Fiscal Periods: {FiscalPeriod.objects.count()}")
print()
print("Next: Access /accounting/dashboard/")
print()
