"""
Creates the mpesa_configurations table if it doesn't exist, then inserts/updates
the production config row with the correct callback URLs derived from SITE_URL.

Run with:  python fix_mpesa_config.py
"""
import os, django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.db import connection
from django.conf import settings

SITE_URL          = getattr(settings, 'SITE_URL', 'https://grazuri.uzuriapps.xyz').rstrip('/')
VALIDATION_URL    = f"{SITE_URL}/payments/callback/validation/"
CONFIRMATION_URL  = f"{SITE_URL}/payments/callback/confirmation/"
SHORTCODE         = '4159523'
CONSUMER_KEY      = '9mD1A3H1qw5grqdqkZ4X1G9zbNxioydHXL5An4nkUGRlNRKr'
CONSUMER_SECRET   = 'C2dqBSaGFUIporfYYuyhQgnfPEqLvCS3GvfAJ91ENkXI2bhqptlVXAqMelsEpLQR'

print(f"Target domain : {SITE_URL}")
print(f"Validation    : {VALIDATION_URL}")
print(f"Confirmation  : {CONFIRMATION_URL}")
print()

with connection.cursor() as cur:
    # ------------------------------------------------------------------ #
    # 1. Create the table if it doesn't exist                             #
    # ------------------------------------------------------------------ #
    cur.execute("""
        CREATE TABLE IF NOT EXISTS `mpesa_configurations` (
            `id`                  CHAR(32)     NOT NULL PRIMARY KEY,
            `environment`         VARCHAR(20)  NOT NULL DEFAULT 'production',
            `consumer_key`        VARCHAR(100) NOT NULL,
            `consumer_secret`     VARCHAR(100) NOT NULL,
            `business_short_code` VARCHAR(10)  NOT NULL,
            `passkey`             VARCHAR(100) DEFAULT NULL,
            `validation_url`      VARCHAR(200) NOT NULL,
            `confirmation_url`    VARCHAR(200) NOT NULL,
            `response_type`       VARCHAR(20)  NOT NULL DEFAULT 'Completed',
            `is_active`           TINYINT(1)   NOT NULL DEFAULT 1,
            `created_at`          DATETIME(6)  NOT NULL,
            `updated_at`          DATETIME(6)  NOT NULL
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
    """)
    print("✅ Table mpesa_configurations exists (created or already present)")

    # ------------------------------------------------------------------ #
    # 2. Check if a row for this shortcode already exists                 #
    # ------------------------------------------------------------------ #
    cur.execute(
        "SELECT id FROM mpesa_configurations WHERE business_short_code = %s LIMIT 1",
        [SHORTCODE]
    )
    row = cur.fetchone()

    if row:
        # Update the callback URLs (and credentials in case they changed)
        cur.execute("""
            UPDATE mpesa_configurations
               SET validation_url   = %s,
                   confirmation_url = %s,
                   consumer_key     = %s,
                   consumer_secret  = %s,
                   environment      = 'production',
                   is_active        = 1,
                   updated_at       = NOW()
             WHERE business_short_code = %s
        """, [VALIDATION_URL, CONFIRMATION_URL, CONSUMER_KEY, CONSUMER_SECRET, SHORTCODE])
        print(f"✅ Updated existing config row (id={row[0]})")
    else:
        import uuid
        new_id = uuid.uuid4().hex
        cur.execute("""
            INSERT INTO mpesa_configurations
                (id, environment, consumer_key, consumer_secret,
                 business_short_code, passkey,
                 validation_url, confirmation_url,
                 response_type, is_active, created_at, updated_at)
            VALUES (%s, 'production', %s, %s, %s, '',
                    %s, %s, 'Completed', 1, NOW(), NOW())
        """, [new_id, CONSUMER_KEY, CONSUMER_SECRET, SHORTCODE,
              VALIDATION_URL, CONFIRMATION_URL])
        print(f"✅ Inserted new config row (id={new_id})")

# ------------------------------------------------------------------ #
# 3. Attempt to re-register the URLs with Safaricom                   #
# ------------------------------------------------------------------ #
print("\n🔄 Registering URLs with Safaricom ...")
try:
    from payments.models import MpesaConfiguration
    from payments.services import MpesaService
    config = MpesaConfiguration.objects.get(business_short_code=SHORTCODE)
    service = MpesaService(config)
    result = service.register_urls(
        validation_url=VALIDATION_URL,
        confirmation_url=CONFIRMATION_URL,
    )
    print(f"✅ Safaricom registration response: {result}")
except Exception as e:
    print(f"⚠️  Safaricom registration failed: {e}")
    print("   Register the URLs manually in the M-Pesa portal if needed.")

print("\nDone.")
