#!/usr/bin/env python
"""
Daraja Migration Setup Script
==============================
Hardcoded, non-interactive. Connects to MySQL directly with pymysql
(same pattern as fix_final_issues.py — no Django settings involved).

  1. Writes M-Pesa Daraja credentials to .env
  2. Renames lipia_* columns to mpesa_* in developer_payments table
  3. Records migrations 0008 + 0009 in django_migrations table

Run from project root:  python setup_daraja.py

© PhinTech Solutions Company Ltd
"""

import os
import sys
from datetime import datetime

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

# ── HARDCODED: Database ──────────────────────────────────────────────────────
DB = dict(
    host='localhost',
    port=3306,
    database='xygbfpsg_loans',
    user='xygbfpsg_graz',
    password='j.ez-xy6##y.rllB',
    charset='utf8mb4',
)

# ── HARDCODED: M-Pesa Daraja ──────────────────────────────────────────────────
# Daraja app: Prod-PHINTECH SOLUTIONS-1782745321201
DARAJA_ENV_VARS = {
    "DB_NAME": "xygbfpsg_loans",
    "DB_USER": "xygbfpsg_graz",
    "DB_PASSWORD": "j.ez-xy6##y.rllB",
    "DB_HOST": "localhost",
    "DB_PORT": "3306",
    "MPESA_DEV_CONSUMER_KEY": "P5K0wSGunjLUsA3ScyItbSUS5nvIk8vGJ5WTeG8JlYAjrPWw",
    "MPESA_DEV_CONSUMER_SECRET": "DyGp3b8IGW8q6ePhpETGpHGrkBnFfaHizrNroVC1xZqoW3G2zpHd7H3N3ivscm4v",
    "MPESA_DEV_PASSKEY": "9c79f92c1fe6fe1144dfdb4a4543d0d0b8772f52f43d125f611e772121c507e8",
    "MPESA_DEV_SHORTCODE": "4501895",
    "MPESA_DEV_ENVIRONMENT": "production",
    "MPESA_DEV_CALLBACK_URL": "https://grazuri.uzuriapps.xyz/payments/developer/callback/daraja/",
}

ENV_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), ".env")

SEP = '=' * 60
NOW = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')


def step(msg):
    print(f"\n{SEP}\n  {msg}\n{SEP}")


def update_env_file():
    """Force-write all credentials to .env. Overwrites existing values for known keys."""
    all_vars = DARAJA_ENV_VARS

    lines = []
    if os.path.exists(ENV_FILE):
        with open(ENV_FILE, "r", encoding="utf-8") as f:
            lines = f.readlines()
    else:
        lines = ["# .env\n"]

    written_keys = set()
    new_lines = []

    for line in lines:
        stripped = line.strip()
        if stripped and not stripped.startswith("#") and "=" in stripped:
            key = stripped.split("=", 1)[0].strip()
            if key in all_vars:
                new_lines.append(f"{key}={all_vars[key]}\n")
                written_keys.add(key)
                continue
        new_lines.append(line)

    for key, value in all_vars.items():
        if key not in written_keys:
            new_lines.append(f"{key}={value}\n")
            written_keys.add(key)

    with open(ENV_FILE, "w", encoding="utf-8") as f:
        f.writelines(new_lines)

    print(f"Wrote {len(all_vars)} credentials to .env:")
    for key in all_vars:
        print(f"  + {key}")


def column_exists(cur, table, column):
    """Check if a column exists in a table."""
    cur.execute("""
        SELECT COUNT(*) as cnt FROM information_schema.COLUMNS
        WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s AND COLUMN_NAME = %s
    """, [DB['database'], table, column])
    return cur.fetchone()['cnt'] > 0


def migration_applied(cur, app, name):
    """Check if a Django migration has been recorded."""
    cur.execute("""
        SELECT COUNT(*) as cnt FROM django_migrations
        WHERE app = %s AND name = %s
    """, [app, name])
    return cur.fetchone()['cnt'] > 0


def record_migration(cur, conn, app, name):
    """Insert a record into django_migrations."""
    cur.execute("""
        INSERT INTO django_migrations (app, name, applied)
        VALUES (%s, %s, %s)
    """, [app, name, NOW])
    conn.commit()


def run_migrations():
    """Connect to MySQL directly and run the schema changes."""
    conn = pymysql.connect(**DB)
    cur = conn.cursor(pymysql.cursors.DictCursor)

    # ── Migration 0008: Rename lipia_* columns to mpesa_* ────────────────────
    mig_0008 = '0008_developer_payment_daraja'

    if migration_applied(cur, 'payments', mig_0008):
        print(f"Migration {mig_0008} already applied — skipping.")
    else:
        changes = []

        # lipia_checkout_id → mpesa_checkout_id
        if column_exists(cur, 'developer_payments', 'lipia_checkout_id'):
            cur.execute("""
                ALTER TABLE developer_payments
                CHANGE COLUMN lipia_checkout_id mpesa_checkout_id VARCHAR(200) NULL
            """)
            changes.append('lipia_checkout_id → mpesa_checkout_id')

        # lipia_transaction_id → mpesa_transaction_id
        if column_exists(cur, 'developer_payments', 'lipia_transaction_id'):
            cur.execute("""
                ALTER TABLE developer_payments
                CHANGE COLUMN lipia_transaction_id mpesa_transaction_id VARCHAR(200) NULL
            """)
            changes.append('lipia_transaction_id → mpesa_transaction_id')

        if changes:
            conn.commit()
            print(f"Renamed columns: {', '.join(changes)}")
        else:
            print("Columns already renamed (mpesa_* exist, lipia_* not found).")

        record_migration(cur, conn, 'payments', mig_0008)
        print(f"Recorded migration {mig_0008}")

    # ── Migration 0009: help_text changes (no schema change in MySQL) ────────
    mig_0009 = '0009_alter_developerpayment_mpesa_checkout_id_and_more'

    if migration_applied(cur, 'payments', mig_0009):
        print(f"Migration {mig_0009} already applied — skipping.")
    else:
        # 0009 only changes help_text (Django metadata, not stored in MySQL).
        # No ALTER TABLE needed — just record it so Django doesn't try to re-run.
        record_migration(cur, conn, 'payments', mig_0009)
        print(f"Recorded migration {mig_0009} (help_text only, no schema change)")

    conn.close()


def main():
    step("STEP 1/2 — Writing credentials to .env")
    update_env_file()

    step("STEP 2/2 — Running migrations via direct MySQL connection")
    run_migrations()

    step("DONE")
    print(f"Callback: {DARAJA_ENV_VARS['MPESA_DEV_CALLBACK_URL']}")
    print("\nNext steps:")
    print("  1. Deploy code to production (grazuri.uzuriapps.xyz)")
    print("  2. Register callback URL in Daraja portal")
    print("  3. Test with a KES 1 payment")


if __name__ == "__main__":
    main()
