import json
import mysql.connector

PROGRESS_FILE = 'c:/fuentes/proyectos delphi/GESTION DOCUMENTAL/RAUL_ASENCIO/revision_progreso.json'

with open(PROGRESS_FILE, 'r', encoding='utf-8') as f:
    data = json.load(f)

cifs_validos = {
    'F23839327': 1,
    'B19856855': 2,
    'B19897628': 3,
    'F55476741': 4,
    'B19897610': 5
}

empresas_nom = {
    1: 'RAUL ASENCIO COOP.V. (CIF: F23839327)',
    2: 'RAUL ASENCIO PASTELERIAS S.L. (CIF: B19856855)',
    3: 'PASTELERIA LA TERE S.L.E (CIF: B19897628)',
    4: 'AYN CONSULTING COOP. V. (CIF: F55476741)',
    5: 'ALHARRUBA S.L. (CIF: B19897610)'
}

strict_reassign = []
for k, v in data.items():
    cif = (v.get('cif_detectado') or '').upper().replace('-', '').replace(' ', '').replace('.', '')
    if cif in cifs_validos:
        matched_id = cifs_validos[cif]
        if matched_id != v.get('empresa_actual'):
            v['id_detectado_estricto'] = matched_id
            strict_reassign.append(v)

print(f"Total de documentos a reasignar con CIF validado en ge_empresas: {len(strict_reassign)}")

conn = mysql.connector.connect(host='85.215.144.168', user='asesoft', password='Pantera1', database='pastelerias', autocommit=False)
cursor = conn.cursor(dictionary=True)

try:
    for item in strict_reassign:
        doc_id = item['doc_id']
        tipo = item['tipo']
        old_emp = item['empresa_actual']
        new_emp = item['id_detectado_estricto']
        num_doc = item['num_doc']
        prov = item['prov']
        
        print(f"\nProcesando Doc {doc_id} [{tipo} {num_doc}] - Prov: {prov}")
        print(f"  Cambio de empresa: {old_emp} ({empresas_nom.get(old_emp)}) -> {new_emp} ({empresas_nom.get(new_emp)})")

        if tipo == 'ALBARAN':
            id_alb = item['id_albaran']
            # 1. Cabecera albarán
            cursor.execute('UPDATE ge_prov_albaranes SET idempresa = %s WHERE id = %s', (new_emp, id_alb))
            print(f"    ge_prov_albaranes (id={id_alb}): {cursor.rowcount} filas actualizadas")
            # 2. Líneas detalle albarán
            cursor.execute('UPDATE ge_prov_albaranes_detalle SET idempresa = %s WHERE idalbaran = %s', (new_emp, id_alb))
            print(f"    ge_prov_albaranes_detalle (idalbaran={id_alb}): {cursor.rowcount} líneas actualizadas")
            # 3. Documento gráfico
            cursor.execute('UPDATE ge_documentos SET id_empresa = %s WHERE id = %s', (new_emp, doc_id))
            print(f"    ge_documentos (id={doc_id}): {cursor.rowcount} filas actualizadas")

        elif tipo == 'FACTURA':
            id_fac = item['id_factura']
            # 1. Cabecera factura
            cursor.execute('UPDATE ge_prov_facturas SET idempresa = %s WHERE id = %s', (new_emp, id_fac))
            print(f"    ge_prov_facturas (id={id_fac}): {cursor.rowcount} filas actualizadas")
            # 2. Líneas detalle factura
            cursor.execute('UPDATE ge_prov_facturas_detalle SET idempresa = %s WHERE idfactura = %s', (new_emp, id_fac))
            print(f"    ge_prov_facturas_detalle (idfactura={id_fac}): {cursor.rowcount} líneas actualizadas")
            # 3. Documento gráfico
            cursor.execute('UPDATE ge_documentos SET id_empresa = %s WHERE id = %s', (new_emp, doc_id))
            print(f"    ge_documentos (id={doc_id}): {cursor.rowcount} filas actualizadas")

    conn.commit()
    print("\n" + "="*60)
    print("¡TODAS LAS REASIGNACIONES SE HAN COMPLETADO Y CONFIRMADO CON ÉXITO!")
    print("="*60)

except Exception as e:
    conn.rollback()
    print(f"\nERROR durante la actualización, se realizó ROLLBACK: {e}")
    raise
finally:
    cursor.close()
    conn.close()
