#!/usr/bin/env python3
"""
Seeds the two config_file_versions rows the load test needs
(emv_config + application, active, for vendor="LoadTest" model="mf919"),
pointing at small fixture files already added under
TMS_UAT/priv/static/loadtest/.

Deliberately does NOT seed a parameter_template or a keys_config row —
PushGate skips a type entirely when TargetVersionCache has no active target
for it, so leaving those two unseeded is what keeps the load test's gap
devices from touching the MMS DB (parameter push needs a real
pos_terminal/pos_merchant row) or the RKI HTTP endpoint (keys_config push).
See config.py's comment on gap_fraction for the full reasoning.

Idempotent: re-running just leaves the existing active row in place.
"""
import sys

import pymysql

from config import SETTINGS


def get_or_create(cur, config_type, file_path, version):
    cur.execute(
        """
        SELECT id, is_active FROM config_file_versions
        WHERE config_type=%s AND vendor=%s AND model=%s AND version=%s
        """,
        (config_type, SETTINGS.vendor, SETTINGS.model, version),
    )
    row = cur.fetchone()
    if row:
        row_id, is_active = row
        if not is_active:
            cur.execute("UPDATE config_file_versions SET is_active=1 WHERE id=%s", (row_id,))
        print(f"  {config_type}: reusing existing row id={row_id}")
        return row_id

    cur.execute(
        """
        INSERT INTO config_file_versions
            (config_type, vendor, model, version, file_path, is_active,
             release_notes, inserted_at, updated_at)
        VALUES (%s, %s, %s, %s, %s, 1, %s, NOW(), NOW())
        """,
        (
            config_type,
            SETTINGS.vendor,
            SETTINGS.model,
            version,
            file_path,
            "Seeded by tools/terminal-heartbeat/seed.py for the heartbeat load test. Safe to delete.",
        ),
    )
    row_id = cur.lastrowid
    print(f"  {config_type}: created row id={row_id}")
    return row_id


def main():
    conn = pymysql.connect(
        host=SETTINGS.db_host,
        user=SETTINGS.db_user,
        password=SETTINGS.db_password_or_exit(),
        database=SETTINGS.db_name,
        autocommit=True,
    )
    try:
        with conn.cursor() as cur:
            print(f"Seeding config_file_versions for vendor={SETTINGS.vendor!r} model={SETTINGS.model!r} "
                  f"in database {SETTINGS.db_name!r} ...")
            emv_id = get_or_create(cur, "emv_config", SETTINGS.emv_source_rel_path, SETTINGS.target_emv_version)
            app_id = get_or_create(cur, "application", SETTINGS.app_source_rel_path, SETTINGS.target_app_version)
        print("Done.")
        print(f"  emv_config config_file_versions.id = {emv_id}")
        print(f"  application config_file_versions.id = {app_id}")
        print()
        print("These take effect once TargetVersionCache reloads (on the app's periodic "
              "refresh, or immediately if the app is (re)started after this seed).")
    finally:
        conn.close()


if __name__ == "__main__":
    sys.exit(main())
