"""
diagnose_manual_payments.py
===========================
Run this ON THE PRODUCTION SERVER to find out why specific payments
were entered manually instead of being caught automatically by SasaPay.

Usage (on the server):
    python diagnose_manual_payments.py

What it does:
    1. Looks up Antony Mwenda Mwangi's manual payment (Oct 23 2026 11:15)
       and all other manual payments from the repayments page you shared.
    2. For each one, checks the sasapay_ipn_logs table around the same time
       to see whether an IPN arrived — and if so, WHY it was dropped.
    3. Also checks sasapay_unknown_payments for any matching bill_ref/msisdn.
    4. Prints a clear diagnosis for every payment.
"""

import json
import sys
import os
import subprocess
from datetime import datetime, timedelta

# ── Auto-install PyMySQL if no MySQL driver is available ───────────────────
def _ensure_driver():
    for mod in ('pymysql', 'MySQLdb', 'mysql.connector'):
        try:
            __import__(mod)
            return  # already have one
        except ImportError:
            continue
    print("  [DB] No MySQL driver found — installing PyMySQL...")
    try:
        subprocess.check_call(
            [sys.executable, '-m', 'pip', 'install', '--quiet', '--user', 'pymysql'],
            stdout=subprocess.DEVNULL,
        )
        print("  [DB] PyMySQL installed successfully.")
    except subprocess.CalledProcessError as e:
        print(f"  [DB] pip install failed: {e}")
        print("  Try manually: pip install pymysql --user")
        sys.exit(1)

_ensure_driver()

# ── Production DB credentials ──────────────────────────────────────────────
DB_HOST     = 'localhost'
DB_PORT     = 3306
DB_NAME     = 'xygbfpsg_loans'
DB_USER     = 'xygbfpsg_graz'
DB_PASSWORD = 'j.ez-xy6##y.rllB'

# ── Connect using whatever MySQL library is available ──────────────────────
def get_connection():
    # 1. Try PyMySQL (most common on shared hosting)
    try:
        import pymysql
        conn = pymysql.connect(
            host=DB_HOST, port=DB_PORT, database=DB_NAME,
            user=DB_USER, password=DB_PASSWORD,
            charset='utf8mb4',
            cursorclass=pymysql.cursors.DictCursor,
        )
        print("  [DB] Connected via PyMySQL")
        return conn, 'pymysql'
    except ImportError:
        pass

    # 2. Try mysqlclient / MySQLdb
    try:
        import MySQLdb
        import MySQLdb.cursors
        conn = MySQLdb.connect(
            host=DB_HOST, port=DB_PORT, db=DB_NAME,
            user=DB_USER, passwd=DB_PASSWORD,
            charset='utf8mb4',
            cursorclass=MySQLdb.cursors.DictCursor,
        )
        print("  [DB] Connected via MySQLdb")
        return conn, 'mysqldb'
    except ImportError:
        pass

    # 3. Try mysql-connector-python
    try:
        import mysql.connector
        conn = mysql.connector.connect(
            host=DB_HOST, port=DB_PORT, database=DB_NAME,
            user=DB_USER, password=DB_PASSWORD,
            charset='utf8mb4',
        )
        # wrap to return dicts
        class DictCursorWrapper:
            def __init__(self, raw_conn):
                self._cur = raw_conn.cursor(dictionary=True)
            def execute(self, sql, args=None):
                self._cur.execute(sql, args or [])
            def fetchall(self):
                return self._cur.fetchall()
            def fetchone(self):
                return self._cur.fetchone()
            def close(self):
                self._cur.close()
        class ConnWrapper:
            def __init__(self, c): self._c = c
            def cursor(self, **_): return DictCursorWrapper(self._c)
            def close(self): self._c.close()
        print("  [DB] Connected via mysql-connector-python")
        return ConnWrapper(conn), 'connector'
    except ImportError:
        pass

    # 4. Fall back to Django's own ORM connection
    try:
        script_dir = os.path.dirname(os.path.abspath(__file__))
        sys.path.insert(0, script_dir)
        os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
        import django
        django.setup()
        from django.db import connection as dj_conn

        class DjangoCursorWrapper:
            def __init__(self): self._cur = dj_conn.cursor()
            def execute(self, sql, args=None):
                self._cur.execute(sql, args or [])
            def fetchall(self):
                cols = [c[0] for c in self._cur.description]
                return [dict(zip(cols, row)) for row in self._cur.fetchall()]
            def fetchone(self):
                cols = [c[0] for c in self._cur.description]
                row = self._cur.fetchone()
                return dict(zip(cols, row)) if row else None
            def close(self): self._cur.close()

        class DjangoConnWrapper:
            def cursor(self, **_): return DjangoCursorWrapper()
            def close(self): pass

        print("  [DB] Connected via Django ORM connection")
        return DjangoConnWrapper(), 'django'
    except Exception as e:
        print(f"\nERROR: Could not connect to the database with any available driver.")
        print(f"  Install PyMySQL:  pip install pymysql")
        print(f"  Details: {e}")
        sys.exit(1)

# ── Manual payments to investigate (from the page you shared) ──────────────
# Format: (borrower_name, phone, loan_number, amount, payment_date_approx)
MANUAL_PAYMENTS = [
    ('Antony Mwenda Mwangi',    '+254791053223', 'BSH/202503/00067', 5000,   '2026-10-23 11:15'),
    ('Peris Njambi Kinuthia',   '+254716919075', 'LOAN-000040',      400,    '2026-10-22 11:12'),
    ('Jane Nyokabi Wambura',    '+254724633735', 'BSH/202512/00151', 2000,   '2026-10-22 11:11'),
    ('Kiiru Jane Wanjiku',      '+254725267165', 'LOAN-000020',      2000,   '2026-10-21 11:28'),
    ('Sammy Mengo Ndungu',      '+254724346307', 'LOAN-000014',      2000,   '2026-10-21 11:20'),
    ('Esther Njeri Wangari',    '0708584121',    'LOAN-000030',      5000,   '2026-10-21 11:19'),
    ('Lucy Wangari Githinji',   '+254715741516', 'LOAN-000007',      3000,   '2026-10-21 11:18'),
    ('Rose Wairimu Njuguna',    '+254727564254', 'LOAN-000044',      700,    '2026-10-21 11:13'),
    ('Humphrey Syrus Njoroge',  '+254721950985', 'LOAN-000042',      12500,  '2026-10-20 12:24'),
    ('purity waithira wangeka', '0725912251',    'LOAN-000023',      4000,   '2026-10-20 12:24'),
]

SEP = '─' * 80

def phone_variants(phone):
    """Generate all three Kenyan format variants of a phone number."""
    p = str(phone).strip()
    variants = {p}
    if p.startswith('0') and len(p) == 10:
        variants.add('+254' + p[1:])
        variants.add('254'  + p[1:])
    elif p.startswith('+254') and len(p) == 13:
        variants.add(p[1:])
        variants.add('0' + p[4:])
    elif p.startswith('254') and len(p) == 12:
        variants.add('+' + p)
        variants.add('0' + p[3:])
    return list(variants)

def last9(phone):
    digits = ''.join(c for c in str(phone) if c.isdigit())
    return digits[-9:] if len(digits) >= 9 else digits


def run():
    print(f"\n{'═'*80}")
    print("  MANUAL PAYMENT DIAGNOSTIC — Haven Grazuri Production DB")
    print(f"{'═'*80}\n")

    conn, _driver = get_connection()
    cur = conn.cursor()

    # ── SECTION 1: Verify borrower phone numbers are stored correctly ──────
    print("SECTION 1: Borrower phone numbers in the users_customuser table")
    print(SEP)

    phones_checked = {}
    for name, phone, loan_num, amount, dt in MANUAL_PAYMENTS:
        variants = phone_variants(phone)
        placeholders = ','.join(['%s'] * len(variants))
        cur.execute(f"""
            SELECT id, first_name, last_name, phone_number, is_active, role
            FROM users
            WHERE phone_number IN ({placeholders})
              AND role = 'borrower'
        """, variants)
        rows = cur.fetchall()
        if rows:
            r = rows[0]
            stored = r['phone_number']
            active = '✅ Active' if r['is_active'] else '❌ INACTIVE'
            match  = '✅ exact' if stored == phone else f'⚠️  stored as {stored!r} (input was {phone!r})'
            print(f"  {name:<35} {match}  {active}")
            phones_checked[phone] = stored
        else:
            # Try last-9 suffix
            suffix = last9(phone)
            cur.execute("""
                SELECT id, first_name, last_name, phone_number, is_active, role
                FROM users
                WHERE phone_number LIKE %s AND role = 'borrower'
            """, [f'%{suffix}'])
            rows2 = cur.fetchall()
            if rows2:
                stored = rows2[0]['phone_number']
                print(f"  {name:<35} ⚠️  NOT found by exact variant — last-9 found {stored!r}")
                phones_checked[phone] = stored
            else:
                print(f"  {name:<35} ❌ NOT FOUND IN DB at all (phone={phone!r})")
                phones_checked[phone] = None

    # ── SECTION 2: Check IPN logs around the time of each manual payment ───
    print(f"\nSECTION 2: SasaPay IPN log entries near each manual payment time")
    print(SEP)

    for name, phone, loan_num, amount, dt_str in MANUAL_PAYMENTS:
        dt = datetime.strptime(dt_str, '%Y-%m-%d %H:%M')
        window_start = dt - timedelta(hours=6)
        window_end   = dt + timedelta(hours=1)

        stored_phone = phones_checked.get(phone)
        variants     = phone_variants(phone)
        suffix       = last9(phone)

        print(f"\n  [{name}]  {phone}  |  Loan: {loan_num}  |  KES {amount}  |  Manual entry: {dt_str}")

        # Search IPN logs by BillRefNumber (inside raw_data JSON) and by date window
        cur.execute("""
            SELECT id, trans_id, processing_status, processing_note,
                   receipt_number, created_at, raw_data
            FROM sasapay_ipn_logs
            WHERE created_at BETWEEN %s AND %s
            ORDER BY created_at
        """, [window_start, window_end])
        ipn_rows = cur.fetchall()

        if not ipn_rows:
            print(f"    📭 NO IPN logs at all in window {window_start:%H:%M}–{window_end:%H:%M}")
            print(f"       → SasaPay never delivered an IPN for this payment period.")
            print(f"       → Possible causes: customer paid after business hours and staff entered")
            print(f"         it next morning; or SasaPay IPN delivery failed silently.")
        else:
            # Check each IPN for a matching bill_ref
            matched_ipns = []
            all_ipns_in_window = []
            for row in ipn_rows:
                try:
                    d = row['raw_data'] if isinstance(row['raw_data'], dict) else json.loads(row['raw_data'])
                except Exception:
                    d = {}
                bill_ref  = (d.get('BillRefNumber') or '').strip()
                msisdn    = (d.get('MSISDN') or '').strip()
                ipn_amount = d.get('TransAmount', '?')
                all_ipns_in_window.append({
                    'trans_id': row['trans_id'],
                    'bill_ref': bill_ref,
                    'msisdn':   msisdn,
                    'amount':   ipn_amount,
                    'status':   row['processing_status'],
                    'note':     row['processing_note'],
                    'time':     row['created_at'],
                })
                # Match by bill_ref variants or last-9
                bill_variants = phone_variants(bill_ref) if bill_ref else []
                if (bill_ref in variants or
                    any(v in bill_variants for v in variants) or
                    (suffix and bill_ref.endswith(suffix)) or
                    loan_num.lower() in bill_ref.lower()):
                    matched_ipns.append({**all_ipns_in_window[-1], 'raw': d})

            if matched_ipns:
                for ipn in matched_ipns:
                    status = ipn['status']
                    note   = ipn['note'] or '—'
                    print(f"    ✅ IPN FOUND: TransID={ipn['trans_id']}  BillRef={ipn['bill_ref']!r}")
                    print(f"       Amount={ipn['amount']}  Time={ipn['time']}")
                    if status == 'processed':
                        print(f"       Status: ✅ PROCESSED → receipt {ipn.get('receipt_number','?')}")
                        print(f"       NOTE: IPN was processed but staff ALSO entered it manually → DUPLICATE!")
                    elif status == 'no_match':
                        print(f"       Status: ❌ NO_MATCH")
                        print(f"       Why: BillRef {ipn['bill_ref']!r} didn't match any borrower phone/ID/loan")
                        print(f"       Stored phone in DB: {stored_phone!r}")
                        bf_variants = phone_variants(ipn['bill_ref'])
                        print(f"       BillRef variants tried: {bf_variants}")
                        print(f"       DB phone variants:      {variants}")
                        overlap = set(bf_variants) & set(variants)
                        if overlap:
                            print(f"       ⚠️  OVERLAP EXISTS ({overlap}) — matcher should have worked!")
                            print(f"       → Bug: pre-fix code was running at this time")
                        else:
                            print(f"       → No overlap: customer typed {ipn['bill_ref']!r} but stored as {stored_phone!r}")
                    elif status == 'no_loan':
                        print(f"       Status: ❌ NO_LOAN — borrower matched but had no active loan")
                        print(f"       Note: {note}")
                    elif status == 'no_balance':
                        print(f"       Status: ❌ NO_BALANCE — loan was fully paid when IPN arrived")
                    elif status == 'failed':
                        print(f"       Status: ❌ FAILED — processing error")
                        print(f"       Error: {note}")
                    elif status == 'duplicate':
                        print(f"       Status: ⏭️  DUPLICATE — already processed earlier")
                    else:
                        print(f"       Status: {status} | Note: {note}")
            else:
                print(f"    ⚠️  {len(all_ipns_in_window)} IPN(s) in window but NONE matched this borrower's phone/loan")
                print(f"       IPNs in window:")
                for ipn in all_ipns_in_window[:5]:
                    print(f"         TransID={ipn['trans_id']}  BillRef={ipn['bill_ref']!r}  "
                          f"Amount={ipn['amount']}  Status={ipn['status']}")
                print(f"       → Customer likely paid using a different reference (not their phone number)")

        # Also check unknown_payments table
        cur.execute("""
            SELECT id, amount, paid_by, msisdn, bill_ref, reference, notes, resolved, created_at
            FROM sasapay_unknown_payments
            WHERE created_at BETWEEN %s AND %s
        """, [window_start, window_end])
        unknown_rows = cur.fetchall()
        matching_unknown = [
            r for r in unknown_rows
            if (last9(r['bill_ref'] or '') == suffix or
                last9(r['msisdn'] or '')    == suffix or
                loan_num.lower() in (r['bill_ref'] or '').lower())
        ]
        if matching_unknown:
            for u in matching_unknown:
                resolved = '✅ resolved' if u['resolved'] else '❌ STILL PENDING'
                print(f"    📋 UNKNOWN PAYMENT: KES {u['amount']}  BillRef={u['bill_ref']!r}  "
                      f"MSISDN={u['msisdn']!r}  {resolved}")
                print(f"       Notes: {u['notes']}")

    # ── SECTION 3: Pattern analysis — what time were manual payments entered?
    print(f"\n\nSECTION 3: Pattern — manual payment times vs auto payment times")
    print(SEP)

    cur.execute("""
        SELECT
            HOUR(payment_date) AS hour,
            COUNT(*) AS total,
            SUM(CASE WHEN payment_source='automatic' THEN 1 ELSE 0 END) AS auto_count,
            SUM(CASE WHEN payment_source='manual'    THEN 1 ELSE 0 END) AS manual_count
        FROM repayments
        WHERE payment_date >= '2026-09-01'
          AND payment_method = 'mpesa'
        GROUP BY HOUR(payment_date)
        ORDER BY HOUR(payment_date)
    """)
    rows = cur.fetchall()
    print(f"  {'Hour':>6}  {'Auto':>6}  {'Manual':>8}  Bar")
    for r in rows:
        bar = '█' * int(r['auto_count'] or 0) + '░' * int(r['manual_count'] or 0)
        flag = ' ← peak manual entry time' if r['manual_count'] > r['auto_count'] else ''
        print(f"  {r['hour']:02d}:00   {r['auto_count']:>5}   {r['manual_count']:>7}   {bar[:50]}{flag}")

    # ── SECTION 4: Specific Antony IPN lookup (broader search) ────────────
    print(f"\n\nSECTION 4: Deep dive — all IPN logs mentioning Antony / 791053223")
    print(SEP)

    cur.execute("""
        SELECT id, trans_id, processing_status, processing_note, receipt_number, created_at, raw_data
        FROM sasapay_ipn_logs
        WHERE (raw_data LIKE '%791053223%' OR raw_data LIKE '%Mwenda%' OR raw_data LIKE '%Antony%')
          AND created_at >= '2026-10-01'
        ORDER BY created_at DESC
        LIMIT 20
    """)
    antony_rows = cur.fetchall()
    if antony_rows:
        for r in antony_rows:
            try:
                d = r['raw_data'] if isinstance(r['raw_data'], dict) else json.loads(r['raw_data'])
            except Exception:
                d = {}
            print(f"  {r['created_at']}  TransID={r['trans_id']}  Status={r['processing_status']}")
            print(f"    BillRef={d.get('BillRefNumber','?')!r}  Amount={d.get('TransAmount','?')}  "
                  f"Name={d.get('FirstName','')} {d.get('LastName','')}")
            if r['processing_note']:
                print(f"    Note: {r['processing_note']}")
    else:
        print("  No IPN logs found for Antony in October 2026.")
        print("  → Confirms: SasaPay never delivered an IPN for his Oct 23 payment.")

    # ── SECTION 5: Overall IPN health stats ───────────────────────────────
    print(f"\n\nSECTION 5: Overall IPN health (all time)")
    print(SEP)

    cur.execute("""
        SELECT processing_status, COUNT(*) AS cnt
        FROM sasapay_ipn_logs
        GROUP BY processing_status
        ORDER BY cnt DESC
    """)
    for r in cur.fetchall():
        bar = '█' * min(r['cnt'] // 5, 40)
        print(f"  {r['processing_status']:<15} {r['cnt']:>5}  {bar}")

    cur.execute("SELECT COUNT(*) AS cnt FROM sasapay_unknown_payments WHERE resolved=0")
    pending_unknown = cur.fetchone()['cnt']
    print(f"\n  Unknown payments still pending resolution: {pending_unknown}")

    cur.execute("""
        SELECT COUNT(*) AS cnt FROM repayments
        WHERE payment_source='manual' AND payment_method='mpesa'
          AND payment_date >= '2026-10-01'
    """)
    manual_oct = cur.fetchone()['cnt']
    cur.execute("""
        SELECT COUNT(*) AS cnt FROM repayments
        WHERE payment_source='automatic' AND payment_method='mpesa'
          AND payment_date >= '2026-10-01'
    """)
    auto_oct = cur.fetchone()['cnt']
    total_oct = manual_oct + auto_oct
    pct = (manual_oct / total_oct * 100) if total_oct else 0
    print(f"\n  October 2026 M-Pesa payments:")
    print(f"    Auto:   {auto_oct}")
    print(f"    Manual: {manual_oct}  ({pct:.1f}% of total)")

    # ── SECTION 6: Proof check — compare IPN log count vs auto repayments ──
    # This is the key question: are there manual repayments whose M-Pesa
    # transaction time has NO corresponding IPN log entry at all?
    # If yes → SasaPay never sent the IPN. If no → system dropped it.
    print(f"\n\nSECTION 6: Proof — manual repayments with zero IPN evidence")
    print(SEP)
    print("  Checking each manual M-Pesa repayment since Sep 1 2026:")
    print("  For each one we look for ANY IPN log within ±3 hours of same amount.\n")

    cur.execute("""
        SELECT r.receipt_number, r.amount, r.payment_date, r.mpesa_transaction_id,
               r.mpesa_phone_number,
               l.loan_number,
               u.first_name, u.last_name, u.phone_number
        FROM repayments r
        JOIN loans l ON l.id = r.loan_id
        JOIN users u ON u.id = l.borrower_id
        WHERE r.payment_source = 'manual'
          AND r.payment_method = 'mpesa'
          AND r.payment_date >= '2026-09-01'
        ORDER BY r.payment_date DESC
        LIMIT 60
    """)
    manual_rows = cur.fetchall()

    no_ipn_count   = 0
    has_ipn_count  = 0
    server_err_count = 0

    for mr in manual_rows:
        pd = mr['payment_date']
        amt = float(mr['amount'])
        w_start = pd - timedelta(hours=3)
        w_end   = pd + timedelta(hours=3)

        # Any IPN with same amount in window?
        cur.execute("""
            SELECT id, trans_id, processing_status, raw_data
            FROM sasapay_ipn_logs
            WHERE created_at BETWEEN %s AND %s
              AND raw_data LIKE %s
        """, [w_start, w_end, f'%{int(amt) if amt == int(amt) else amt}%'])
        ipn_hits = cur.fetchall()

        # Filter to same-amount IPNs
        matching = []
        for h in ipn_hits:
            try:
                d = h['raw_data'] if isinstance(h['raw_data'], dict) else json.loads(h['raw_data'])
                if abs(float(d.get('TransAmount', 0)) - amt) < 0.01:
                    matching.append(h)
            except Exception:
                pass

        name = f"{mr['first_name']} {mr['last_name']}"
        loan = mr['loan_number']

        if not matching:
            no_ipn_count += 1
            # Extra check: was the server returning errors at this time?
            cur.execute("""
                SELECT COUNT(*) AS cnt FROM sasapay_ipn_logs
                WHERE created_at BETWEEN %s AND %s
            """, [w_start, w_end])
            ipns_in_window = cur.fetchone()['cnt']
            server_note = f"({ipns_in_window} other IPNs DID arrive in window — server was up)" \
                          if ipns_in_window > 0 else "(NO IPNs at all in window — server may have been down or SasaPay didn't send)"
            print(f"  ❌ NO IPN: {name:<35} KES {amt:<8.0f} {pd.strftime('%d/%m %H:%M')}  {loan}")
            print(f"             {server_note}")
        else:
            has_ipn_count += 1
            # IPN existed — why didn't it auto-process?
            for h in matching:
                try:
                    d = h['raw_data'] if isinstance(h['raw_data'], dict) else json.loads(h['raw_data'])
                    bill_ref = d.get('BillRefNumber', '?')
                except Exception:
                    bill_ref = '?'
                status = h['processing_status']
                print(f"  ⚠️  IPN EXISTS but manual entry: {name:<30} KES {amt:<8.0f} "
                      f"Status={status} BillRef={bill_ref!r}")

    print(f"\n  ── Summary ──")
    print(f"  Manual repayments with NO IPN evidence at all : {no_ipn_count}  ← SasaPay's fault")
    print(f"  Manual repayments where IPN DID arrive        : {has_ipn_count}  ← system's fault (or staff duplicate)")
    total_checked = no_ipn_count + has_ipn_count
    if total_checked:
        sasapay_pct = no_ipn_count / total_checked * 100
        system_pct  = has_ipn_count / total_checked * 100
        print(f"\n  VERDICT:")
        print(f"    {sasapay_pct:.0f}% of manual entries → SasaPay never sent the IPN")
        print(f"    {system_pct:.0f}% of manual entries → IPN arrived but system failed to process")
        if sasapay_pct >= 80:
            print(f"\n  ✅ CONCLUSION: The manual entries are overwhelmingly caused by")
            print(f"     SasaPay NOT delivering IPNs to your server.")
            print(f"     Your system code is NOT the problem for these payments.")
        elif system_pct >= 50:
            print(f"\n  ⚠️  CONCLUSION: The system is dropping a significant portion of IPNs.")
            print(f"     Check the IPN gaps page for processing errors.")
        else:
            print(f"\n  ⚠️  CONCLUSION: Mixed — both SasaPay delivery gaps and system drops.")

    cur.close()
    conn.close()
    print(f"\n{'═'*80}")
    print("  Diagnostic complete.")
    print(f"{'═'*80}\n")


if __name__ == '__main__':
    run()
