#!/usr/bin/env python
"""
Final Accounting Deployment - handles migrations and setup
"""

import os
import sys
from pathlib import Path

print("=" * 60)
print("Final Accounting System Deployment")
print("=" * 60)
print()

# Load .env
from dotenv import load_dotenv
BASE_DIR = Path(__file__).resolve().parent
load_dotenv(BASE_DIR / '.env', override=True)

# Set Django settings
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
os.environ['DB_USER'] = os.getenv('DB_USER', 'xygbfpsg_graz')
os.environ['DB_PASSWORD'] = os.getenv('DB_PASSWORD', '')
os.environ['DB_NAME'] = os.getenv('DB_NAME', 'xygbfpsg_loans')

import django
django.setup()

from django.db import connection
from accounting.models import Account, FiscalPeriod
from users.models import CustomUser
from datetime import datetime, timedelta

# Check if tables exist
print("[1/3] Checking database tables...")
with connection.cursor() as cursor:
    cursor.execute("SHOW TABLES LIKE 'accounting_accounts'")
    accounts_table_exists = cursor.fetchone() is not None
    
    cursor.execute("SHOW TABLES LIKE 'accounting_fiscal_periods'")
    periods_table_exists = cursor.fetchone() is not None

if not accounts_table_exists or not periods_table_exists:
    print("  ✗ Accounting tables don't exist")
    print()
    print("  Run these commands first:")
    print("  1. python manage.py makemigrations accounting")
    print("  2. python manage.py migrate accounting --fake-initial")
    print("  3. python manage.py migrate")
    print()
    sys.exit(1)

print("  ✓ Tables exist")
print()

# Create Chart of Accounts
print("[2/3] Creating Chart of Accounts...")
system_user = CustomUser.objects.filter(role='admin').first()

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
for acc in accounts:
    _, 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']}")

print(f"  Created: {created} accounts")
print()

# Create Fiscal Periods
print("[3/3] Creating Fiscal Periods...")
year = datetime.now().year
created = 0

for month in range(1, 13):
    start = datetime(year, month, 1).date()
    end = (datetime(year, 12, 31) if month == 12 else (datetime(year, month + 1, 1) - timedelta(days=1))).date()
    
    _, 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

_, 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")
print()

print("=" * 60)
print("SUCCESS!")
print("=" * 60)
print(f"Accounts: {Account.objects.count()}")
print(f"Fiscal Periods: {FiscalPeriod.objects.count()}")
print()
print("Access: /accounting/dashboard/")
print()
