"""
restore_borrower_names.py v4
-----------------------------
Positional mapping: loan_applications were created by migrating loan_info rows
in order. APP-000001 = first loan_info row (by id), APP-000002 = second, etc.
We verify each match by checking the loan amount agrees.
"""
import pymysql, re, os, csv
from io import StringIO
from collections import defaultdict

DB = dict(host="localhost", port=3306, db="xygbfpsg_loans",
          user="xygbfpsg_graz", password="j.ez-xy6##y.rllB",
          charset="utf8mb4", autocommit=False)
conn = pymysql.connect(**DB)

BORROWERS_SQL = os.path.join(os.path.dirname(os.path.abspath(__file__)), "borrowers.sql")

def q(sql, p=None):
    with conn.cursor() as cur:
        cur.execute(sql, p or [])
        return cur.fetchall()

def norm_phone(phone):
    if not phone: return None
    p = str(phone).strip().replace(' ','').replace('-','')
    if p.startswith('07') and len(p) == 10: return '+254' + p[1:]
    if p.startswith('01') and len(p) == 10: return '+254' + p[1:]
    if p.startswith('254') and len(p) == 12: return '+' + p
    if p.startswith('+254') and len(p) == 13: return p
    return None

def unique_username(cur, base, uuid):
    candidate = base[:30]
    suffix = 1
    while True:
        cur.execute("SELECT id FROM users WHERE username=%s AND id!=%s", [candidate, uuid])
        if not cur.fetchone(): return candidate
        candidate = f"{base[:27]}_{suffix}"
        suffix += 1

print("=" * 70)
print("  restore_borrower_names.py v4")
print("=" * 70)

# ── 1. Parse borrowers.sql ────────────────────────────────────────────────────
print(f"\n[1] Parsing borrowers.sql …")
with open(BORROWERS_SQL, "r", encoding="utf-8", errors="replace") as f:
    sql_text = f.read()

COLS = ['id','fname','middlename','lname','email','phone','telephone',
        'addrs1','addrs2','district','country','comment','account','image',
        'date_time','status','date_of_birth','gender','id_number','passport',
        'credit_score','employment_status','employer','title','created_by',
        'modified_by','balance','emp_code','salary','disposable_income',
        'occupation','modified_on','postal','ownershipType','member','marital',
        'marriageType','nationality','city','state','zip','added_by','branch']

values_match = re.search(r'INSERT INTO `borrowers`[^;]+VALUES\s*(.*?);', sql_text, re.DOTALL)
raw_block = values_match.group(1).strip() if values_match else ''
row_re = re.compile(r'\(([^()]*(?:\'[^\']*\'[^()]*)*)\)', re.DOTALL)

borrowers = {}
for raw in row_re.findall(raw_block):
    try:
        parts = next(csv.reader(StringIO(raw), quotechar="'", skipinitialspace=True))
        if len(parts) < len(COLS): continue
        row = dict(zip(COLS, parts))
        borrowers[int(row['id'])] = row
    except Exception:
        pass
print(f"    Parsed {len(borrowers)} borrowers")

# ── 2. Build the positional map ───────────────────────────────────────────────
print(f"\n[2] Building positional map …")

# loan_info ordered by id: each row = one loan, borrower=int_id
# Multiple rows can share the same borrower (multiple loans)
# We need: for each unique borrower in loan_info, what APP does their first
# (and subsequent) loans correspond to?

# Key insight: loan_applications APP numbers are sequential per borrower entry
# order. Get the unique borrower sequence from loan_info ordered by id.
# That sequence = the order borrowers were first seen = order of APP creation.

# Step A: loan_info ordered by id → list of (li_id, borrower_int, amount)
li_rows = q("SELECT id, borrower, amount FROM loan_info ORDER BY id")

# Step B: loan_applications ordered by APP number → (app_num, borrower_uuid, amount)
app_rows = q("""
    SELECT application_number, borrower_id, requested_amount
    FROM loan_applications
    ORDER BY CAST(SUBSTRING(application_number, 5) AS UNSIGNED)
""")

print(f"    loan_info rows: {len(li_rows)}  loan_applications rows: {len(app_rows)}")

# Step C: show the alignment for inspection
print(f"\n    Alignment check (loan_info ↔ loan_applications):")
print(f"    {'LI_ID':>6}  {'INT_ID':>6}  {'LI_AMT':>10}  {'APP_NUM':<14}  {'APP_AMT':>10}  {'UUID_PREFIX'}")
print(f"    {'-'*80}")
for i, ((li_id, b_int, li_amt), (app_num, b_uuid, app_amt)) in enumerate(zip(li_rows, app_rows)):
    match = "✓" if abs(float(li_amt or 0) - float(app_amt or 0)) < 1 else "✗"
    print(f"    {li_id:>6}  {b_int:>6}  {float(li_amt or 0):>10.0f}  {app_num:<14}  {float(app_amt or 0):>10.0f}  {b_uuid[:16]}  {match}")

# ── 3. Build uuid_to_int from positional alignment ───────────────────────────
print(f"\n[3] Building uuid→int_id from positional alignment …")

uuid_to_int = {}
mismatches = 0
for (li_id, b_int, li_amt), (app_num, b_uuid, app_amt) in zip(li_rows, app_rows):
    amt_match = abs(float(li_amt or 0) - float(app_amt or 0)) < 1
    if not amt_match:
        print(f"    MISMATCH at {app_num}: loan_info amt={li_amt} app amt={app_amt} — skipping")
        mismatches += 1
        continue
    # A borrower may appear multiple times; use last mapping (same int_id anyway)
    uuid_to_int[b_uuid] = int(b_int)

print(f"    Positional matches: {len(uuid_to_int)}  mismatches: {mismatches}")

# ── 4. Update users ───────────────────────────────────────────────────────────
print(f"\n[4] Updating {len(uuid_to_int)} users …")
updated = skipped = 0

try:
    with conn.cursor() as cur:
        for uuid, int_id in uuid_to_int.items():
            b = borrowers.get(int_id)
            if not b:
                print(f"    WARN: int_id {int_id} not in borrowers.sql")
                skipped += 1
                continue

            fname  = (b.get('fname','') or '').strip().strip("'")
            lname  = (b.get('lname','') or '').strip().strip("'")
            phone  = norm_phone(b.get('phone','') or b.get('telephone',''))
            email  = (b.get('email','') or '').strip().strip("'") or None
            id_num = (b.get('id_number','') or '').strip().strip("'") or None
            g_raw  = (b.get('gender','') or '').strip().strip("'").lower()
            gender = 'M' if g_raw in ('male','m') else ('F' if g_raw in ('female','f') else None)
            dob    = (b.get('date_of_birth','') or '').strip().strip("'")
            if dob in ('0000-00-00','1900-01-01','','NULL','None'): dob = None
            addr   = (b.get('addrs1','') or '').replace('\\r\\n',' ').strip().strip("'") or None
            city   = (b.get('city','') or b.get('district','') or '').strip().strip("'") or None
            county = (b.get('state','') or '').strip().strip("'") or None

            base = f"{fname.lower()}.{lname.lower()}".replace(' ','')[:28] if fname and lname else f"borrower_{uuid[:8]}"
            username = unique_username(cur, base, uuid)

            if phone:
                cur.execute("SELECT id FROM users WHERE phone_number=%s AND id!=%s", [phone, uuid])
                if cur.fetchone(): phone = None
            if id_num:
                cur.execute("SELECT id FROM users WHERE id_number=%s AND id!=%s", [id_num, uuid])
                if cur.fetchone(): id_num = None

            cur.execute("""
                UPDATE users SET
                    first_name=%s, last_name=%s,
                    phone_number=COALESCE(%s,phone_number),
                    email=COALESCE(NULLIF(TRIM(%s),''),email),
                    id_number=COALESCE(NULLIF(TRIM(%s),''),id_number),
                    gender=COALESCE(%s,gender),
                    date_of_birth=COALESCE(%s,date_of_birth),
                    physical_address=COALESCE(NULLIF(TRIM(%s),''),physical_address),
                    city=COALESCE(NULLIF(TRIM(%s),''),city),
                    county=COALESCE(NULLIF(TRIM(%s),''),county),
                    username=%s
                WHERE id=%s
            """, [fname, lname, phone, email, id_num, gender, dob,
                  addr, city, county, username, uuid])

            if cur.rowcount:
                updated += 1
                print(f"    ✓ {uuid[:16]}… → {fname} {lname}  {phone or '(no phone)'}")
            else:
                skipped += 1

    conn.commit()
    print(f"\n    Updated: {updated}  skipped: {skipped}")

except Exception as e:
    conn.rollback()
    import traceback; traceback.print_exc()
    conn.close()
    exit(1)

# ── 5. Remaining placeholders ─────────────────────────────────────────────────
print(f"\n[5] Remaining placeholders …")
remaining = q("SELECT id, first_name, last_name, phone_number FROM users WHERE first_name='Borrower' AND role='borrower'")
if remaining:
    print(f"    {len(remaining)} unmatched:")
    for r in remaining: print(f"      {r[0]}  {r[1]} {r[2]}  {r[3]}")
else:
    print("    All borrowers updated ✓")

conn.close()
print(f"\n{'='*70}\n  Done.\n{'='*70}")
