#!/bin/bash
# Fix PostgreSQL GROUP BY bug in ERPNext's payment_ledger_entry.py
#
# Run on the server:
#   ssh root@96.125.196.67
#   bash fix_ple_postgres.sh
#
# The bug: update_voucher_outstanding() selects 'account', 'party_type', 'party'
# columns but doesn't include them in GROUP BY. PostgreSQL requires all non-aggregated
# columns to be in GROUP BY.

set -e

CONTAINER="erpnext-backend-1"
FILE="apps/erpnext/erpnext/accounts/doctype/payment_ledger_entry/payment_ledger_entry.py"
BENCH_DIR="/home/frappe/frappe-bench"

echo "=== Fix PLE PostgreSQL GROUP BY bug ==="

# Show current groupby lines
echo "Current groupby patterns:"
docker exec $CONTAINER grep -n "groupby" $BENCH_DIR/$FILE

echo ""
echo "Applying fix..."

# The fix: find .groupby lines that have voucher_type and voucher_no
# and add account, party_type, party
# We use a Python script inside the container for reliable patching
docker exec $CONTAINER python3 -c "
import re

filepath = '$BENCH_DIR/$FILE'
with open(filepath, 'r') as f:
    content = f.read()

# Pattern: .groupby(ple.voucher_type, ple.voucher_no) without account
# We need to handle both single-line and multi-line groupby
original = content

# Fix 1: Single-line groupby
content = re.sub(
    r'\.groupby\(\s*ple\.voucher_type\s*,\s*ple\.voucher_no\s*\)',
    '.groupby(ple.voucher_type, ple.voucher_no, ple.account, ple.party_type, ple.party)',
    content
)

if content != original:
    with open(filepath, 'w') as f:
        f.write(content)
    print('PATCHED: Added account, party_type, party to GROUP BY')
else:
    # Try multi-line pattern
    content = re.sub(
        r'(\.groupby\([^)]*ple\.voucher_type[^)]*ple\.voucher_no)(\s*\))',
        r'\1, ple.account, ple.party_type, ple.party\2',
        original
    )
    if content != original:
        with open(filepath, 'w') as f:
            f.write(content)
        print('PATCHED (multi-line): Added account, party_type, party to GROUP BY')
    else:
        print('WARNING: Could not find pattern to patch. Check manually:')
        # Show the function for manual inspection
        import ast
        lines = original.split('\n')
        for i, line in enumerate(lines):
            if 'groupby' in line.lower():
                start = max(0, i-2)
                end = min(len(lines), i+3)
                for j in range(start, end):
                    print(f'  {j+1}: {lines[j]}')
                print()
"

echo ""
echo "After fix:"
docker exec $CONTAINER grep -n "groupby" $BENCH_DIR/$FILE

echo ""
echo "Restarting workers..."
docker restart $CONTAINER
echo ""
echo "=== Done! Wait 30s for container to start, then run bulk_submit ==="
