#!/usr/bin/env python3
"""#24981 P5 — prueba de carga de la captura en costeo_cambio (triggers de detmov).

Compara DOS variantes en un MySQL descartable (NO produccion, NO el servidor de pruebas):
  A = triggers de hoy (existencias_tienda + maeplu_cambios)
  D = A + la captura REAL que genera Instalacion.php (se genera con genera_triggers.php)
Carga: N hilos, cada uno D documentos de L lineas; HOT% de las lineas sobre 5 PLU "calientes"; el documento
se reintenta al interbloqueo (1213) y se cuentan los interbloqueos. Las variantes se ALTERNAN entre rondas.

Uso: COSTEO_P5_PASS=<clave> carga.py <puerto> [rondas=3] [hilos=8] [docs=300] [lineas=10]
Requisitos: python3 con `pymysql` (pip install pymysql), `php` y `composer install` hecho en la raiz del repo
(genera_triggers.php carga el autoload); un MySQL 8.0 DESCARTABLE en 127.0.0.1:<puerto> (docker run mysql:8.0).
Falla (exit 1) si un hilo muere o no se conecta, si no se completan todos los documentos, o si D pierde marcas.
Se NEGARA a correr si el servidor tiene otras bases de usuario ademas de p5c (proteccion contra apuntarlo a un
servidor real). NO se reutiliza el script archivado de la medicion del 18-oct.
"""
import json, os, random, statistics, subprocess, sys, threading, time
import pymysql

PUERTO, CLAVE = int(sys.argv[1]), os.environ.get('COSTEO_P5_PASS', '')
RONDAS = int(sys.argv[2]) if len(sys.argv) > 2 else 3
HILOS = int(sys.argv[3]) if len(sys.argv) > 3 else 8
DOCS = int(sys.argv[4]) if len(sys.argv) > 4 else 300
LINEAS = int(sys.argv[5]) if len(sys.argv) > 5 else 10
HOT = 0.5
DIR = __import__('os').path.dirname(__import__('os').path.abspath(__file__))


def conn(db=None, ac=True):
    return pymysql.connect(host='127.0.0.1', port=PUERTO, user='root', password=CLAVE, database=db,
                           autocommit=ac, client_flag=pymysql.constants.CLIENT.MULTI_STATEMENTS)


SCHEMA = """
DROP DATABASE IF EXISTS p5c; CREATE DATABASE p5c; USE p5c;
CREATE TABLE detmov (id BIGINT AUTO_INCREMENT PRIMARY KEY, tienda FLOAT(10,0), tipodoc FLOAT(10,0), fecha DATE,
  plu VARCHAR(20), movimiento VARCHAR(1), cantidad FLOAT(10,0), costo FLOAT(10,0), sicosto FLOAT(10,0),
  KEY plu (plu), KEY fecha (fecha)) ENGINE=InnoDB;
CREATE TABLE existencias_tienda (tienda FLOAT(10,0) NOT NULL, plu VARCHAR(20) NOT NULL, existencia DOUBLE NOT NULL DEFAULT 0,
  PRIMARY KEY (tienda, plu)) ENGINE=InnoDB;
CREATE TABLE maeplu_cambios (id BIGINT AUTO_INCREMENT PRIMARY KEY, plu VARCHAR(20), tipo VARCHAR(10), fecha DATE,
  fecha_hora DATETIME, imagen CHAR(1)) ENGINE=InnoDB;
"""
# Cuerpo de hoy de los tres triggers (equivalente a los de crearTriggersWeb, sin filtro server_id: produccion esta en ROW)
BASE = {
    'INSERT': "INSERT INTO existencias_tienda SET tienda=new.tienda,plu=new.plu,existencia=IF(new.movimiento='E',new.cantidad,-new.cantidad) ON DUPLICATE KEY UPDATE existencia=existencia+IF(new.movimiento='E',new.cantidad,-new.cantidad); INSERT INTO maeplu_cambios SET plu=new.plu,tipo='UPDATE',fecha=CURRENT_DATE,fecha_hora=CURRENT_TIMESTAMP,imagen='N';",
    'UPDATE': "INSERT INTO existencias_tienda SET tienda=old.tienda,plu=old.plu,existencia=IF(old.movimiento='E',old.cantidad,-old.cantidad) ON DUPLICATE KEY UPDATE existencia=existencia-IF(old.movimiento='E',old.cantidad,-old.cantidad); INSERT INTO existencias_tienda SET tienda=new.tienda,plu=new.plu,existencia=IF(new.movimiento='E',new.cantidad,-new.cantidad) ON DUPLICATE KEY UPDATE existencia=existencia+IF(new.movimiento='E',new.cantidad,-new.cantidad); INSERT INTO maeplu_cambios SET plu=new.plu,tipo='UPDATE',fecha=CURRENT_DATE,fecha_hora=CURRENT_TIMESTAMP,imagen='N';",
    'DELETE': "INSERT INTO existencias_tienda SET tienda=old.tienda,plu=old.plu,existencia=IF(old.movimiento='E',old.cantidad,-old.cantidad) ON DUPLICATE KEY UPDATE existencia=existencia-IF(old.movimiento='E',old.cantidad,-old.cantidad); INSERT INTO maeplu_cambios SET plu=old.plu,tipo='UPDATE',fecha=CURRENT_DATE,fecha_hora=CURRENT_TIMESTAMP,imagen='N';",
}
OPS = {'INSERT': 'AFTER INSERT', 'UPDATE': 'AFTER UPDATE', 'DELETE': 'AFTER DELETE'}


def captura_real():
    """Cuerpos de los tres triggers EXACTAMENTE como los genera Instalacion.php (con captura)."""
    out = subprocess.check_output(['php', DIR + '/genera_triggers.php', json.dumps(BASE)])
    return json.loads(out)


def instalar(variante, real):
    c = conn('p5c')
    cur = c.cursor()
    for ev in OPS:
        cur.execute("DROP TRIGGER IF EXISTS t_" + ev.lower())
        cuerpo = real[ev] if variante == 'D' else BASE[ev]
        cur.execute("CREATE TRIGGER t_%s %s ON detmov FOR EACH ROW BEGIN %s END" % (ev.lower(), OPS[ev], cuerpo))
    cur.execute("DROP TABLE IF EXISTS costeo_cambio")
    if variante == 'D':
        cur.execute(open(DIR + '/../../docs/costeo/costeo_cambio.sql').read())
    cur.execute("TRUNCATE detmov; TRUNCATE existencias_tienda; TRUNCATE maeplu_cambios")
    c.close()


def worker(k, res, errores):
    rng = random.Random(1000 + k)
    hot = [1, 2, 3, 4, 5]
    lat, dead = [], 0
    try:
        c = conn('p5c', ac=False)  # un fallo de conexion tambien invalida la corrida
        cur = c.cursor()
        for d in range(DOCS):
            filas = []
            for _ in range(LINEAS):
                n = rng.choice(hot) if rng.random() < HOT else rng.randint(1, 500)
                filas.append(('P%04d' % n, rng.randint(1, 6), rng.choice('ES'), rng.randint(1, 20)))
            t0 = time.time()
            while True:
                try:
                    for plu, tienda, mov, cant in filas:
                        cur.execute("INSERT INTO detmov (tienda,tipodoc,fecha,plu,movimiento,cantidad,costo,sicosto) "
                                    "VALUES (%s,5,'2026-10-01',%s,%s,%s,2.5,1)", (tienda, plu, mov, cant))
                    c.commit()
                    break
                except pymysql.err.OperationalError as e:
                    c.rollback()
                    if e.args[0] == 1213:
                        dead += 1
                        continue
                    raise
            lat.append((time.time() - t0) * 1000)
    except Exception as e:  # un hilo caido invalida la corrida
        errores.append(repr(e))
    res[k] = (lat, dead)


def ronda(variante, real):
    instalar(variante, real)
    res, errores = {}, []
    ths = [threading.Thread(target=worker, args=(k, res, errores)) for k in range(HILOS)]
    t0 = time.time()
    [t.start() for t in ths]
    [t.join() for t in ths]
    el = time.time() - t0
    if errores:
        sys.exit('HILO CAIDO (corrida invalida): %s' % errores[0])
    if len(res) != HILOS or any(len(r[0]) != DOCS for r in res.values()):
        sys.exit('CORRIDA INCOMPLETA: terminaron %d de %d hilos o faltan documentos' % (len(res), HILOS))
    lat = sorted(x for r in res.values() for x in r[0])
    dead = sum(r[1] for r in res.values())
    c = conn('p5c'); cur = c.cursor()
    cur.execute("SELECT COUNT(*) FROM detmov"); lineas = cur.fetchone()[0]
    marcas = None
    if variante == 'D':
        cur.execute("SELECT COUNT(*) FROM costeo_cambio"); marcas = cur.fetchone()[0]
        if marcas != lineas:
            sys.exit('D PERDIO MARCAS: %s marcas para %s lineas' % (marcas, lineas))
    c.close()
    return dict(v=variante, lineas_s=round(lineas / el), doc_p50=round(lat[len(lat) // 2], 2),
                doc_p99=round(lat[int(len(lat) * 0.99)], 2), interbloqueos=dead, lineas=lineas, marcas=marcas)


def exigir_servidor_descartable():
    c = conn(); cur = c.cursor()
    cur.execute("SELECT SCHEMA_NAME FROM information_schema.SCHEMATA WHERE SCHEMA_NAME NOT IN "
                "('mysql','information_schema','performance_schema','sys','p5c')")
    otras = [r[0] for r in cur.fetchall()]
    c.close()
    if otras:
        sys.exit('NO CORRO: el servidor tiene otras bases (%s). Esto solo corre en un MySQL descartable.' % ', '.join(otras[:5]))


if __name__ == '__main__':
    exigir_servidor_descartable()
    c = conn(); c.cursor().execute(SCHEMA); c.close()
    real = captura_real()
    ronda('A', real)  # calentamiento, descartada
    out = []
    for i in range(RONDAS):
        orden = ('A', 'D') if i % 2 == 0 else ('D', 'A')
        for v in orden:
            r = ronda(v, real); r['ronda'] = i; out.append(r); print(json.dumps(r), flush=True)
    for v in ('A', 'D'):
        xs = [r for r in out if r['v'] == v]
        print(json.dumps(dict(resumen=v, lineas_s_mediana=statistics.median(r['lineas_s'] for r in xs),
                              interbloqueos_mediana=statistics.median(r['interbloqueos'] for r in xs),
                              doc_p99_mediana=statistics.median(r['doc_p99'] for r in xs))))
