"""
fix_legacy_gl_entries.py
========================
Removes legacy LOAN-DISB- and LOAN-REPAY- journal entries that were
posted to wrong account codes (202001, 202003) by the old IntegrationService.

The correct DISB- and REP- entries already exist for the same transactions.
This script just removes the duplicates on the wrong accounts.

Run:  python fix_legacy_gl_entries.py
"""
import sys
from decimal import Decimal

try:
    import pymysql
except ImportError:
    import subprocess
    subprocess.check_call([sys.executable,'-m','pip','install','--quiet','--user','pymysql'])
    import pymysql

DB = dict(host='localhost', port=3306, database='xygbfpsg_loans',
          user='xygbfpsg_graz', password='j.ez-xy6##y.rllB',
          charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)

SEP = '=' * 70

conn = pymysql.connect(**DB)
cur  = conn.cursor()

print()
print(SEP)
print("  GL Legacy Entry Fix")
print(SEP)

# ── Step 1: Identify all legacy prefixes to remove ─────────────────────────
# These are entries posted to wrong account codes by the old IntegrationService
LEGACY_PREFIXES = ['LOAN-DISB-', 'LOAN-REPAY-', 'LOAN-FEE-', 'LOAN-INT-']

print("\n  Legacy entries to remove:")
total_entries = 0
for prefix in LEGACY_PREFIXES:
    cur.execute("""
        SELECT COUNT(*) n, COALESCE(SUM(l.debit_amount),0) dr
        FROM accounting_journal_entries e
        JOIN accounting_journal_entry_lines l ON l.journal_entry_id=e.id
        WHERE e.reference_number LIKE %s
    """, [prefix + '%'])
    r = cur.fetchone()
    if r['n'] > 0:
        print(f"    {prefix:20s}  {r['n']:>5} line entries  DR={Decimal(str(r['dr'])):>12,.0f}")
        total_entries += r['n']

if total_entries == 0:
    print("  No legacy entries found. Nothing to do.")
    conn.close()
    sys.exit(0)

print(f"\n  Total line entries to remove: {total_entries}")

# ── Step 2: Also check for INT-RCP- entries (wrong ref format) ─────────────
# These are entries where the reference is INT-RCP-XXXXXX (receipt number)
# instead of INT-LOAN-NUMBER. These were created by an earlier bug.
cur.execute("""
    SELECT COUNT(*) n
    FROM accounting_journal_entries
    WHERE reference_number LIKE 'INT-RCP-%'
""")
int_rcp_count = cur.fetchone()['n']
if int_rcp_count > 0:
    print(f"\n  Also found {int_rcp_count} INT-RCP- entries (wrong reference format)")
    LEGACY_PREFIXES.append('INT-RCP-')

# ── Step 3: Delete GL rows, lines, then entries ────────────────────────────
print("\n  Removing legacy entries...")

for prefix in LEGACY_PREFIXES:
    # Get entry IDs
    cur.execute("""
        SELECT id FROM accounting_journal_entries
        WHERE reference_number LIKE %s
    """, [prefix + '%'])
    entry_ids = [r['id'] for r in cur.fetchall()]
    if not entry_ids:
        continue

    placeholders = ','.join(['%s'] * len(entry_ids))

    # Delete GL rows first (FK dependency)
    cur.execute(f"DELETE FROM accounting_general_ledger WHERE journal_entry_id IN ({placeholders})", entry_ids)
    gl_deleted = cur.rowcount

    # Delete journal entry lines
    cur.execute(f"DELETE FROM accounting_journal_entry_lines WHERE journal_entry_id IN ({placeholders})", entry_ids)
    lines_deleted = cur.rowcount

    # Delete journal entries
    cur.execute(f"DELETE FROM accounting_journal_entries WHERE id IN ({placeholders})", entry_ids)
    entries_deleted = cur.rowcount

    print(f"    {prefix:20s}  removed {entries_deleted} entries, {lines_deleted} lines, {gl_deleted} GL rows")

conn.commit()
print("\n  Legacy entries removed and committed.")

# ── Step 4: Recalculate running balances for affected accounts ─────────────
print("\n  Recalculating GL running balances for affected accounts...")

AFFECTED_CODES = ['1010', '1011', '1013', '1020', '202001', '202003', '4010', '4020', '3010']
for code in AFFECTED_CODES:
    cur.execute("SELECT id, account_type FROM accounting_accounts WHERE code=%s", [code])
    acc = cur.fetchone()
    if not acc:
        continue

    cur.execute("""
        SELECT id, debit_amount, credit_amount
        FROM accounting_general_ledger
        WHERE account_id=%s
        ORDER BY transaction_date ASC, posted_at ASC, id ASC
    """, [acc['id']])
    rows = cur.fetchall()
    if not rows:
        continue

    running = Decimal('0')
    fixed = 0
    for row in rows:
        dr = Decimal(str(row['debit_amount']))
        cr = Decimal(str(row['credit_amount']))
        if acc['account_type'] in ('asset', 'expense'):
            running = running + dr - cr
        else:
            running = running + cr - dr
        if abs(running - Decimal(str(0))) > 0 or True:  # always update
            cur.execute("UPDATE accounting_general_ledger SET balance=%s WHERE id=%s",
                        [float(running), row['id']])
            fixed += 1

    conn.commit()
    print(f"    {code:8s}  recalculated {fixed} GL rows  final balance={running:,.2f}")

# ── Step 5: Final check ────────────────────────────────────────────────────
print("\n  Final balance check:")

cur.execute("""
    SELECT COALESCE(SUM(l.debit_amount),0) dr, COALESCE(SUM(l.credit_amount),0) cr
    FROM accounting_journal_entry_lines l
    JOIN accounting_journal_entries e ON e.id=l.journal_entry_id
    WHERE e.status='posted'
""")
r = cur.fetchone()
dr = Decimal(str(r['dr'])); cr = Decimal(str(r['cr']))
diff = abs(dr - cr)
print(f"    Total debits : KES {dr:>15,.2f}")
print(f"    Total credits: KES {cr:>15,.2f}")
print(f"    Balanced     : {'YES' if diff < Decimal('0.01') else 'NO - diff=' + str(diff)}")

cur.execute("""
    SELECT g.balance
    FROM accounting_general_ledger g
    JOIN accounting_accounts a ON a.id=g.account_id
    WHERE a.code='1020'
    ORDER BY g.transaction_date DESC, g.posted_at DESC
    LIMIT 1
""")
r = cur.fetchone()
gl_portfolio = Decimal(str(r['balance'])) if r else Decimal('0')

cur.execute("""
    SELECT COALESCE(SUM(principal_amount),0) disbursed,
           COALESCE(SUM(amount_paid),0) repaid
    FROM loans WHERE status IN ('active','paid','defaulted','rolled_over','written_off')
      AND is_deleted=0
""")
r = cur.fetchone()
expected = Decimal(str(r['disbursed'])) - Decimal(str(r['repaid']))
diff_portfolio = abs(gl_portfolio - expected)

print(f"\n    GL Loan Portfolio (1020) : KES {gl_portfolio:>12,.2f}")
print(f"    Loans table outstanding  : KES {expected:>12,.2f}")
print(f"    Difference               : KES {diff_portfolio:>12,.2f}  {'OK' if diff_portfolio < Decimal('1000') else 'STILL OFF'}")

conn.close()
print()
print(SEP)
print("  Fix complete. Run verify_accounting.py to confirm.")
print(SEP)
