#!/usr/bin/env python
"""patch_sfp_view.py - Add net income to equity in financial_statements view"""
import sys, os
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, PROJECT_ROOT)
os.environ['DB_NAME']='xygbfpsg_loans'; os.environ['DB_USER']='xygbfpsg_graz'
os.environ['DB_PASSWORD']='j.ez-xy6##y.rllB'; os.environ['DB_HOST']='localhost'
os.environ['DB_PORT']='3306'; os.environ['DJANGO_SETTINGS_MODULE']='branch_system.settings'
try:
    import dotenv as _d; _d.load_dotenv = lambda *a,**kw: None
except ImportError: pass
import django; django.setup()
from django.conf import settings as _s
_s.DATABASES['default'].update({'NAME':'xygbfpsg_loans','USER':'xygbfpsg_graz',
    'PASSWORD':'j.ez-xy6##y.rllB','HOST':'localhost','PORT':'3306'})
from django import db as _db; _db.connections.close_all()

def p(m): print(str(m), flush=True)

views_path = os.path.join(PROJECT_ROOT, 'reports', 'financial_reports_views.py')
with open(views_path, encoding='utf-8') as f:
    src = f.read()

# Normalize to LF for reliable search
src_n = src.replace('\r\n', '\n')

# Find the block we want to patch
OLD = (
    "    total_assets      = sum(Decimal(str(i['amount'] or 0)) for i in asset_items)\n"
    "    total_liabilities = sum(Decimal(str(i['amount'] or 0)) for i in liability_items)\n"
    "    total_equity      = sum(Decimal(str(i['amount'] or 0)) for i in equity_items)\n"
    "    total_le          = total_liabilities + total_equity\n"
    "    balanced          = abs(total_assets - total_le) < Decimal('0.01')\n"
    "    difference        = abs(total_assets - total_le)\n"
)

NEW = (
    "    total_assets      = sum(Decimal(str(i['amount'] or 0)) for i in asset_items)\n"
    "    total_liabilities = sum(Decimal(str(i['amount'] or 0)) for i in liability_items)\n"
    "    total_equity      = sum(Decimal(str(i['amount'] or 0)) for i in equity_items)\n"
    "    # Mid-year: add current net income to equity so SFP balances\n"
    "    try:\n"
    "        from accounting.models import Account as _Acc2\n"
    "        from accounting.services.accounting_service import AccountingService as _AS2\n"
    "        _svc2 = _AS2()\n"
    "        _ytd_i = sum(_svc2.calculate_account_balance(a, as_of_date, None)\n"
    "                     for a in _Acc2.objects.filter(account_type='income', is_active=True))\n"
    "        _ytd_e = sum(_svc2.calculate_account_balance(a, as_of_date, None)\n"
    "                     for a in _Acc2.objects.filter(account_type='expense', is_active=True))\n"
    "        _ni = _ytd_i - _ytd_e\n"
    "        if abs(_ni) > Decimal('0.00'):\n"
    "            equity_items.append({'code': 'NET_INCOME',\n"
    "                'name': 'Current Year Net Income' if _ni >= 0 else 'Current Year Net Loss',\n"
    "                'note': '', 'amount': _ni})\n"
    "            total_equity += _ni\n"
    "    except Exception:\n"
    "        pass\n"
    "    total_le          = total_liabilities + total_equity\n"
    "    balanced          = abs(total_assets - total_le) < Decimal('0.01')\n"
    "    difference        = abs(total_assets - total_le)\n"
)

if OLD in src_n:
    patched = src_n.replace(OLD, NEW, 1)
    with open(views_path, 'w', encoding='utf-8', newline='\n') as f:
        f.write(patched)
    p("SUCCESS: Patched financial_statements view.")
    p("Net income will now appear in equity section of SFP.")
else:
    p("WARN: target block not found. Showing nearby lines for manual fix:")
    marker = "total_equity      = sum(Decimal(str(i['amount'] or 0)) for i in equity_items)"
    idx = src_n.find(marker)
    if idx >= 0:
        p("Found marker at char " + str(idx))
        ctx = src_n[max(0,idx-100):idx+300]
        p("Context:\n" + ctx)
    else:
        p("Marker not found either. Check file manually.")

# Also patch the default start date in profit_and_loss (Jan 1 of data year)
PL_OLD = "    default_start = today.replace(day=1)\n"
PL_NEW = (
    "    # Default to Jan 1 of earliest GL year so P&L shows full-year data\n"
    "    try:\n"
    "        from accounting.models import GeneralLedger as _GL2\n"
    "        _ed = _GL2.objects.order_by('transaction_date').values_list('transaction_date', flat=True).first()\n"
    "        default_start = __import__('datetime').date(_ed.year, 1, 1) if _ed else today.replace(month=1, day=1)\n"
    "    except Exception:\n"
    "        default_start = today.replace(month=1, day=1)\n"
)

with open(views_path, encoding='utf-8') as f:
    src2 = f.read()
src2_n = src2.replace('\r\n', '\n')

# Find the profit_and_loss function and patch only that occurrence
pl_fn = src2_n.find('def profit_and_loss(')
if pl_fn >= 0:
    pl_old_pos = src2_n.find(PL_OLD, pl_fn)
    if pl_old_pos >= 0:
        src2_n = src2_n[:pl_old_pos] + PL_NEW + src2_n[pl_old_pos + len(PL_OLD):]
        with open(views_path, 'w', encoding='utf-8', newline='\n') as f:
            f.write(src2_n)
        p("SUCCESS: Patched P&L default start date to Jan 1.")
    else:
        p("INFO: P&L default_start already patched or not found.")
else:
    p("WARN: profit_and_loss function not found.")

# Clear Django cache
try:
    from django.core.cache import cache; cache.clear()
    p("Cache cleared.")
except Exception as e:
    p("Cache error: " + str(e))

# Touch restart
import pathlib
wsgi = pathlib.Path(PROJECT_ROOT) / 'passenger_wsgi.py'
if wsgi.exists(): wsgi.touch(); p("Touched passenger_wsgi.py")

p("Done.")