#!/usr/bin/env python3
"""
Final production setup for Haven Grazuri.
- Sets up ONLY Biashara Loan and Log Book Loan products (deactivates all others)
- Configures system settings
- Protects settings_production.py from being overwritten by setup.py

Run on server: python final_setup.py
"""
import os
import sys
import datetime
from decimal import Decimal

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings_production')

try:
    from dotenv import load_dotenv
    load_dotenv(os.path.join(os.path.dirname(os.path.abspath(__file__)), '.env'), override=True)
except ImportError:
    pass

import django
django.setup()

from django.db import connection
from loans.models import LoanProduct, Loan, LoanApplication, Repayment
from users.models import CustomUser

print(f"\n{'='*60}")
print(f"  Haven Grazuri -- Final Production Setup")
print(f"{'='*60}")

# ── 1. Loan products: only Biashara and Log Book ──────────────
print("\n[1] Setting up loan products...")

# Deactivate everything that isn't one of the two real products
deactivated = LoanProduct.objects.exclude(
    name__in=['Biashara Loan', 'Log Book Loan']
).update(is_active=False)
if deactivated:
    print(f"  Deactivated {deactivated} old product(s) (Boost, Mwamba, Imara, General, etc.)")

products = [
    {
        'name': 'Biashara Loan',
        'product_type': 'biashara',
        'description': (
            'Business loan. Weekly repayment. '
            '15% flat rate on principal (Prepaid Loan Interest). '
            'Min KES 2,000 / Max KES 200,000. Duration 1-54 weeks.'
        ),
        'min_amount': Decimal('2000.00'),
        'max_amount': Decimal('200000.00'),
        'min_duration': 7,
        'max_duration': 378,
        'interest_rate': Decimal('15.00'),
        'processing_fee': Decimal('0.00'),
        'gl_code': '11002',
        'grazuri_account_type': 'B',
        'is_active': True,
    },
    {
        'name': 'Log Book Loan',
        'product_type': 'logbook',
        'description': (
            'Logbook secured loan. '
            'Fees: 5% Initiation + 2% Collection + 1% Credit Life + '
            '3.5% Services + 5.5% Administration = 17% total on principal. '
            'Min KES 1,000 / Max KES 1,000,000. Duration 30-365 days.'
        ),
        'min_amount': Decimal('1000.00'),
        'max_amount': Decimal('1000000.00'),
        'min_duration': 30,
        'max_duration': 365,
        'interest_rate': Decimal('17.00'),
        'processing_fee': Decimal('5.00'),
        'gl_code': '11002',
        'grazuri_account_type': 'P',
        'is_active': True,
    },
]

for p in products:
    obj, created = LoanProduct.objects.update_or_create(
        name=p['name'],
        defaults=p
    )
    action = 'Created' if created else 'Updated'
    print(f"  {action}: {p['name']} -- {p['interest_rate']}% flat, "
          f"KES {p['min_amount']:,.0f} to {p['max_amount']:,.0f}")

print(f"\n  Active products now:")
for prod in LoanProduct.objects.filter(is_active=True):
    print(f"    - {prod.name} ({prod.product_type})")

# ── 2. System settings ────────────────────────────────────────
print("\n[2] Configuring system settings...")

try:
    from utils.models import SystemSetting

    settings_to_set = [
        ('company_name',          'Haven Grazuri Investment Limited',
         'Company name'),
        ('company_email',         'havenin2023@gmail.com',
         'Company email'),
        ('company_phone',         '+254112941830',
         'Company phone'),
        ('company_address',       '2nd Floor, Old Jogoo Kimakia Building, Stadium Road, Thika, Kenya',
         'Company address'),
        ('currency',              'KES',
         'Currency code'),
        ('currency_symbol',       'KES',
         'Currency symbol'),
        ('system_version',        '2.0',
         'System version'),
        ('maintenance_mode',      'false',
         'Maintenance mode'),
        ('default_interest_rate', '15',
         'Default interest rate %'),
        ('max_loan_amount',       '1000000',
         'Maximum loan amount'),
        ('min_loan_amount',       '1000',
         'Minimum loan amount'),
        ('late_payment_penalty',  '5',
         'Late payment penalty %'),
        ('loan_approval_required','true',
         'Require loan approval'),
        ('site_url',              'https://uzuriapps.xyz',
         'Site URL'),
        ('loan_products',         'biashara,logbook',
         'Active loan product types'),
    ]

    for key, value, description in settings_to_set:
        obj, created = SystemSetting.objects.update_or_create(
            key=key,
            defaults={'value': value, 'description': description}
        )
        action = 'Created' if created else 'Updated'
        print(f"  {action}: {key} = {value}")

    # Remove any boost/mwamba/imara specific settings
    old_keys = [
        'boost_interest_rate', 'boost_processing_fee',
        'boost_plus_interest_rate', 'boost_plus_processing_fee',
        'mwamba_interest_rate', 'mwamba_processing_fee',
        'imara_interest_rate', 'imara_processing_fee',
    ]
    removed = SystemSetting.objects.filter(key__in=old_keys).delete()
    if removed[0]:
        print(f"  Removed {removed[0]} old Boost/Mwamba/Imara settings")

except Exception as e:
    print(f"  WARNING: Could not set system settings: {e}")
    print(f"  (Set these manually in the admin panel)")

# ── 3. Verify data migration results ─────────────────────────
print("\n[3] Verifying data...")

checks = [
    ("Users (borrowers)",   CustomUser.objects.filter(role='borrower').count()),
    ("Users (admin/staff)", CustomUser.objects.filter(
        role__in=['admin', 'loan_officer', 'team_leader', 'secretary']).count()),
    ("Loan products (active)", LoanProduct.objects.filter(is_active=True).count()),
    ("Loan applications",   LoanApplication.objects.count()),
    ("Loans (total)",       Loan.objects.count()),
    ("Loans (active)",      Loan.objects.filter(status='active').count()),
    ("Repayments",          Repayment.objects.count()),
]

all_good = True
for label, count in checks:
    needs_data = 'product' not in label.lower() and 'staff' not in label.lower()
    flag = "  <- run migrate_data.py first" if count == 0 and needs_data else ""
    if count == 0 and needs_data:
        all_good = False
    print(f"  {label:<30} {count:>8}{flag}")

# ── 4. Protect settings_production.py from setup.py ──────────
print("\n[4] Protecting settings_production.py...")

marker_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), '.production_configured')
with open(marker_file, 'w') as f:
    f.write(f"Production configured on {datetime.datetime.now()}\n")
    f.write("DO NOT DELETE -- prevents setup.py from overwriting settings_production.py\n")
print(f"  Created marker: .production_configured")

# ── Summary ───────────────────────────────────────────────────
print(f"\n{'='*60}")
if all_good:
    print("  ALL DONE -- system is fully configured.")
    print()
    print("  Next steps:")
    print("  1. Restart app in cPanel")
    print("  2. Log in at https://uzuriapps.xyz/login/")
    print("     Email:    admin@havengrazuri.co.ke")
    print("     Password: Grazuri@2026")
    print("  3. Change password immediately after login")
    print("  4. Configure M-Pesa: Settings -> M-Pesa Configuration")
else:
    print("  Some data missing -- run migrate_data.py first, then re-run this.")
print(f"{'='*60}\n")
