#!/usr/bin/env python
"""patch_sfp_view2.py - Replace broken net-income block with correct one"""
import sys, os
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))

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

src = src.replace('\r\n', '\n')

# Find the total_equity sum line and replace everything from there
# down to (and including) the "difference = abs(total_assets - total_le)" line

import re

# Pattern: from total_assets= line to difference= line (the whole block, any version)
pattern = (
    r"    total_assets\s+=\s+sum\(Decimal.*?for i in asset_items\)\n"
    r"    total_liabilities\s+=\s+sum\(Decimal.*?for i in liability_items\)\n"
    r"    total_equity\s+=\s+sum\(Decimal.*?for i in equity_items\)\n"
    r".*?"  # anything in between (the broken patch or nothing)
    r"    difference\s+=\s+abs\(total_assets - total_le\)\n"
)

REPLACEMENT = (
    "    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"
)

match = re.search(pattern, src, re.DOTALL)
if match:
    src = src[:match.start()] + REPLACEMENT + src[match.end():]
    with open(views_path, 'w', encoding='utf-8', newline='\n') as f:
        f.write(src)
    print("SUCCESS: Replaced broken block with correct net-income patch.")
else:
    print("WARN: Pattern not matched. Trying line-by-line approach...")
    # Find the three lines we know exist and their positions
    lines = src.split('\n')
    # Find the index of the total_assets line inside financial_statements view
    # (after 'def financial_statements')
    fn_idx = next((i for i,l in enumerate(lines) if 'def financial_statements' in l), None)
    if fn_idx is None:
        print("ERROR: financial_statements function not found"); sys.exit(1)

    target_idx = None
    for i in range(fn_idx, min(fn_idx+300, len(lines))):
        if "total_assets" in lines[i] and "sum(Decimal" in lines[i] and "asset_items" in lines[i]:
            target_idx = i; break

    if target_idx is None:
        print("ERROR: total_assets line not found after financial_statements"); sys.exit(1)

    print("Found total_assets at line " + str(target_idx+1))

    # Find where the block ends (the line with difference = abs(...total_le...))
    end_idx = None
    for i in range(target_idx, min(target_idx+50, len(lines))):
        if 'difference' in lines[i] and 'total_le' in lines[i] and 'abs' in lines[i]:
            end_idx = i; break

    if end_idx is None:
        print("ERROR: end of block not found"); sys.exit(1)

    print("Block runs from line " + str(target_idx+1) + " to " + str(end_idx+1))
    print("Current content:")
    for l in lines[target_idx:end_idx+1]:
        print("  " + repr(l))

    # Replace lines[target_idx:end_idx+1] with the new block
    new_lines = REPLACEMENT.rstrip('\n').split('\n')
    lines[target_idx:end_idx+1] = new_lines
    src = '\n'.join(lines)
    with open(views_path, 'w', encoding='utf-8', newline='\n') as f:
        f.write(src)
    print("SUCCESS: Replaced block using line-by-line approach.")

# Also fix P&L default start date if not already done
with open(views_path, encoding='utf-8') as f:
    src2 = f.read()
src2 = src2.replace('\r\n', '\n')

if '_ed.year, 1, 1' in src2 or '_GL2' in src2:
    print("INFO: P&L default_start already patched.")
else:
    fn_pl = src2.find('def profit_and_loss(')
    old_line = '    default_start = today.replace(day=1)\n'
    pos = src2.find(old_line, fn_pl) if fn_pl >= 0 else -1
    if pos >= 0:
        new_line = (
            "    try:\n"
            "        from accounting.models import GeneralLedger as _GL2\n"
            "        _ed2 = _GL2.objects.order_by('transaction_date').values_list('transaction_date',flat=True).first()\n"
            "        import datetime as _dt2\n"
            "        default_start = _dt2.date(_ed2.year,1,1) if _ed2 else _dt2.date(today.year,1,1)\n"
            "    except Exception:\n"
            "        import datetime as _dt3\n"
            "        default_start = _dt3.date(today.year,1,1)\n"
        )
        src2 = src2[:pos] + new_line + src2[pos+len(old_line):]
        with open(views_path, 'w', encoding='utf-8', newline='\n') as f:
            f.write(src2)
        print("SUCCESS: Patched P&L default start date.")
    else:
        print("INFO: P&L default_start not found or already patched.")

# Clear cache + restart
import pathlib
try:
    import django, os as _os
    _os.environ.setdefault('DJANGO_SETTINGS_MODULE','branch_system.settings')
    django.setup()
    from django.conf import settings as _s2
    _s2.DATABASES['default'].update({'NAME':'xygbfpsg_loans','USER':'xygbfpsg_graz',
        'PASSWORD':'j.ez-xy6##y.rllB','HOST':'localhost','PORT':'3306'})
    from django.core.cache import cache; cache.clear(); print("Cache cleared.")
except Exception as e: print("Cache: " + str(e))
wsgi = pathlib.Path(PROJECT_ROOT)/'passenger_wsgi.py'
if wsgi.exists(): wsgi.touch(); print("Touched passenger_wsgi.py")
print("Done.")